CMakeLists.txt files for multiple libraries and ex

2019-01-23 06:12发布

问题:

I am just starting playing with CMake. I have something like:

/DEV
 |-- lib1
        | CMakeLists.txt

 |-- lib2
        | CMakeLists.txt

 |-- exe1
        | CMakeLists.txt

/BUILD
 |-- lib1
 |-- lib2
 |-- exe1

/INSTALL
 |-- include
 |-- lib
 |-- bin

I would like to:

  • Build each lib and exe independently when needed. (So I suppose I must add a CMakeLists.txt file for each lib and exe);
  • When building, include and lib directories should reference INSTALL directory; (is it a good idea?)
  • When building, add dependencies to other lib and rebuild them if not up to date.

I dont have any clue where to start. Please help...

回答1:

You don't need individual CMakeLists.txt to build targets independently. Say you have one top level CMakeLists.txt with:

ADD_LIBRARY(lib1 ${all_lib1_files})
ADD_LIBRARY(lib2 ${all_lib2_files})
ADD_EXECUTABLE(exe1 ${all_exe1_files})
TARGET_LINK_LIBRARIES(lib2 lib1)  # lib2 now depends on lib1
TARGET_LINK_LIBRARIES(exe1 lib2)  # exe1 now depends on lib2 and lib1

Then you can build just lib1 by running make lib1 or msbuild lib1.vcxproj, etc. You can achieve the same by having individual CMakeLists.txt files per target - it's up to you if you think it's worth it.

If your project imports these targets using FIND_LIBRARY or FIND_PACKAGE, then they won't be rebuilt if they're not up to date. Ultimately, if you want out-of-date dependencies to be automatically rebuilt, you need to let CMake know about the sources and rules for the dependent target, i.e. the CMakeLists.txt file needs to have added the target using ADD_LIBRARY or ADD_EXECUTABLE.

You shouldn't then need to reference the INSTALL directory (except in INSTALL commands I imagine), since CMake will implicitly use libs/exes build locations rather than installed locations when linking targets.



回答2:

To

Build each lib and exe independently when needed.

just add EXCLUDE_FROM_ALL keyword into add_executable() or add_library() calls.

When building, include and lib directories should reference INSTALL directory

If by referencing you mean adding it to include_directories() and link_directories() then it's not nice. It's better not to assert on location of needed files on user system. The proper way is to locate needed includes and libraries using find_package(), find_library() or find_file(). If you want to use first function, you would need to write FindYourLib.cmake and install it along library itself.

When building, add dependencies to other lib and rebuild them if not up to date

This is done automatically by CMake. Dependencies can be added with add_dependencies() function or implicitly with target_link_libraries().