Search code examples
cmakelinkerstatic-librariesbuild-system

How to properly organize a CMake project with multiple subdirectories?


I have this project structure:

enter image description here

and I'm trying to set CMakeList.txt files properly. My aim is simply linking the library to main.cpp. So I have these CMakeList.txt files:

library/CMakeList.txt: library/CMakeList.txt

source/CMakeList.txt: source/CMakeList.txt

root: enter image description here

When I try to build the project, I get this error: ld: library not found for -lMyLib

Where is the mistake, and how should I properly organize structure for such projects?


Solution

  • You used find_library yet you did not use ${MyLib} variable. Consult find_library documentation.

    You used link_directories, yet it's local to the directory it was used in. Upper directories are unaffected.

    Use an IMPORTED library or an INTERFACE library to link with .a file. See https://stackoverflow.com/a/10550334/9072753 and https://stackoverflow.com/a/41909627/9072753 answers. If it's one library only, I think prefer IMPORTED. Move target_include_directories(Source ...) to library/CMakeLists.txt and instead of Source add include directories to your library, it's conceptually the library include directory.

    I recommend, subjective, depens: move target_include_directories(Source.. inside source/CMakeList.txt. I.e. keep all Source related stuff inside source/CMakeLists.txt. And maybe add EXCLUDE_FROM_ALL to add_subdirectory(library).

    Use set_target_properties instead of set(CMAKE_CXX_STANDARD. Overall, prefer to solely use *target* specific stuff instead of set(...).