Cartesius00
Cartesius00

Reputation: 24364

Multiple library CMakeLists.txt

We have a project P (C/C++ on Linux) consisting of libraries lib1, lib2, lib3.

We have a directory P and extra directories for each of our libs (so, P/lib1/, P/lib2/...). Every library has also its own tests.

Questions:

Upvotes: 23

Views: 33650

Answers (1)

André
André

Reputation: 19337

In this case, I would recommend using a single build/ directory. CMake will likely generate separate lib1, lib2 and lib3 directories in there.

Switching between STATIC vs. SHARED can be done by using the BUILD_SHARED_LIBS flag (check the add_library documentation)

With respect to the CMakeLists.txt organization, the choice is yours:

  1. You can build a single CMakeLists.txt which has multiple add_library entries. This has the benefit that you will get a single CMakeLists.txt, which some people may prefer when the projects are simple.

  2. You could split up your project into multiple CMakeLists.txt distributed over your lib1, lib2 and lib3 directories and use a root cmakelists.txt with add_subdirectory. The benefit of this setup is that it will be easier to generate the build-files with one call (in your build/ directory), but you could then easily step into e.g. lib3/ and call make/msbuild there. CMake will ensure that the dependencies are built correctly

Example 1:

project( P )
# Setup lib1 
set ( LIB1_SOURCES ... ) # Fill in your set of source-files here...
add_library( lib1 ${LIB1_SOURCES} )
# Do similar for lib2 and lib3
target_link_libraries( lib2 lib1 ) # Indicate that lib1 is needed for lib2
target_link_libraries( lib3 lib1 lib2 ) # Indicate that lib2 and lib1 are needed for lib3

Example 2:

project( P )
add_subdirectory( lib1 )
add_subdirectory( lib2 )
add_subdirectory( lib3 )

In each subdirectory you then write your CMakeLists.txt. E.g. in case of lib3:

project( lib3 )
set( LIB3_SOURCES ... ) # Setup the list of sources here.
add_library( lib3 ${LIB3_SOURCES} )
# You can refer to other libraries which should be available from the root cmakelists.
target_link_libraries( lib3 lib1 lib2 )

Upvotes: 38

Related Questions