Maths noob
Maths noob

Reputation: 1802

Cmake configuration for multiple sub-libraries in a "packages" directory

Here is a sample project I am trying to build with a "Packages" directory which includes all the libraries to be used in the main code.

I am trying to keep my root cmake file as clean as possible and avoid relative path such as

include_directory(packages/lib1)

but I am struggling. Is there a way of including sub-directories of a directory for the purposes of header inclusion.

Upvotes: 1

Views: 5547

Answers (1)

Torbjörn
Torbjörn

Reputation: 5820

First a few minor remarks:

include_directories(DIR1 [DIR2 [...]])
Tells CMake where the compiler should look for header files, i.e. -IDIR1 -IDIR2 ....

add_library(NAME [STATIC|SHARED] SOURCES)
This command creates the required compiler commands to create a static or shared library out of a given list of source files. No need to add in the header files. The make target will be called NAME and the library target is known to CMake as NAME.

add_subdirectory(DIR)
Tells CMake to look into DIR and parse the included CMakeLists.txt with all its content.

target_link_libraries(TARGET LIB1 [LIB2 [...]])
Tells CMake to instruct the linker to link LIB1, LIB2, etc. to the TARGET, i.e. -LLIB1 -LLIB2 .... TARGET is a CMake/make target previously defined/created with a call to add_{library,executable,custom_target}.

CMakeLists.txt:

include_directories(libraries)
# a header file in `libraries/lib1/foo.hpp` can be included
# in the whole CMake project by `#include "lib1/foo.hpp"`.
add_subdirectory(libraries)
add_subdirectory(tests)

libraries/CMakeLists.txt:

add_subdirectory(lib1)
add_subdirectory(lib2)

libraries/lib1/CMakeLists.txt:

add_library(lib1 STATIC ${LIB1_SOURCES})

libraries/lib2/CMakeLists.txt:

add_library(lib2 STATIC ${LIB2_SOURCES})

tests/CMakeLists.txt:

add_executable(tests ${TEST_SOURCES})
target_link_libraries(tests lib1 lib2)

Upvotes: 3

Related Questions