0

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:

  1. Create a build-dir at the CMakeLists.txt(A) level

  2. cd into it

  3. run cmake ../

  4. 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!

  • 2
    The hint: target_link_library out to exec is missing. – 273K Mar 16 '23 at 08:21
  • 1
    You may find [this](https://github.com/MhmRhm/CMakeProjectTemplate) useful. It is based on a book called [Modern CMake for C++](https://www.packtpub.com/product/modern-cmake-for-c/9781801070058). In your case I believe you should use [target_link_libraries(out PRIVATE exec)](https://cmake.org/cmake/help/latest/command/target_link_libraries.html) – Mohammad Rahimi Mar 16 '23 at 09:41

0 Answers0