I am trying to compile a very simple C++ program using CMake, but keep having an issue. Following is the directory structure:
CompileTest
|---CMakeLists.txt (A)
|---src
|---CMakeLists.txt (B)
|---main.cc
|---exec
|---CMakeLists.txt (C)
|---exec.cc
|---exec.hh
CMakeLists.txt (A):
cmake_minimum_required(VERSION 3.2)
project(multi_file)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS "-Wall")
add_subdirectory(src)
CMakeLists.txt (B):
add_subdirectory("exec")
add_executable(out main.cc)
CMakeLists.txt (C):
add_library(exec SHARED exec.cc)
exec.cc:
#include <iostream>
#include "exec.hh"
float exec_func(int input)
{
return 0.42f;
}
exec.hh:
#ifndef EXEC_HH_
#define EXEC_HH_
float exec_func(int input);
#endif
main.cc:
#include <iostream>
#include "exec/exec.hh"
int main ()
{
float test = exec_func(2);
std::cout << "test value: " << test << std::endl;
return 0;
}
To run the build:
Create a build-dir at the CMakeLists.txt(A) level
cd into it
run
cmake ../
run
make
If it makes any difference: I am running this test in a docker VM (Ubuntu, gcc12) with a mounted directory
I keep getting the following error:
root@13e768aH4187:/docker-test/CompileTest/builddir# make
[ 25%] Building CXX object src/CMakeFiles/out.dir/main.cc.o
[ 50%] Linking CXX executable out
/usr/bin/ld: CMakeFiles/out.dir/main.cc.o: in function `main':
main.cc:(.text+0x12): undefined reference to `exec_func(int)'
collect2: error: ld returned 1 exit status
make[2]: *** [src/CMakeFiles/out.dir/build.make:97: src/out] Error 1
make[1]: *** [CMakeFiles/Makefile2:115: src/CMakeFiles/out.dir/all] Error 2
make: *** [Makefile:91: all] Error 2
I am confused because all the functions are defined, and I did not see any compilation error. To my understanding, this is caused by a linker error (hence the ld).
Would you mind pointing out what is the issue here?
Thanks!