[CMake] Best practice for static libraries and include files

Alexander Neundorf a.neundorf-work at gmx.net
Fri Mar 8 15:19:50 EST 2013


On Friday 08 March 2013, Alessandro Saccoia wrote:
> Dear list,
> I have one problem that I would like to clarify.
> Sorry for the long post, but it will be very quick to follow.
> 
> Given a directory structure like this (hope it will indent nicely)
> 
> CMakeLists.txt (1)
> 
> |-lib1-CMakeLists.txt (2)
> |
> |       |-src
> |       |
> |           |- lib1.hpp
> |           |- lib1.cpp
> |
> |-lib2-CMakeLists.txt (3)
> |
> |       |-src
> |       |
> |           |- lib2.hpp
> |           |- lib2.cpp
> |       |
> |       |-test
> |       |
> |           |- CMakeLists.txt (4)
> |           |- main.cpp
> 
> with the following dependencies:
> main.cpp -> lib2 -> lib1
> 
> I start with the following (wrong) CMakeFIles (download at
> http://www.keplero.com/upps/SlProblem.tgz). Note that I have explicitly
> left the linking directly out, just to concentrate on include directories.
> 
> CMakeLists.txt (1)
> CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
> PROJECT("Example")
> ADD_SUBDIRECTORY("${PROJECT_SOURCE_DIR}/lib1")
> ADD_SUBDIRECTORY("${PROJECT_SOURCE_DIR}/lib2")
> 
> CMakeLists.txt (2)
> ADD_LIBRARY(lib1 ${CMAKE_CURRENT_SOURCE_DIR}/src/lib1.cpp)
> 
> CMakeLists.txt (3)
> ADD_LIBRARY(lib2 ${CMAKE_CURRENT_SOURCE_DIR}/src/lib2.cpp)
> ADD_SUBDIRECTORY("${CMAKE_CURRENT_SOURCE_DIR}/test")
> 
> CMakeLists.txt (4)
> ADD_EXECUTABLE(foo main.cpp)
> TARGET_LINK_LIBRARIES(foo lib2)
> 
> As lib2.hpp includes lib1.hpp, I get the following error because I haven't
> included the directory where lib1 is. lib2.hpp:5:10: fatal error:
> 'lib1.hpp' file not found
> 
> Before asking this question, I would have defined a global variable in
> CMakeLists.txt (2) SET(lib1_include "${CMAKE_CURRENT_SOURCE_DIR}/src"
> CACHE INTERNAL "lib 1 include")
> 
> and from CMakeLists.txt (3) used
> INCLUDE_DIRECTORIES (${lib1_include})
> 
> Question number 1: is this a good practice?

There is no need to overengineer it.
Just do 
include_directories(${CMAKE_SOURCE_DIR}/lib1/src)
in CMakeLists.txt (3). No need to put it in the cache or something.

> Question n. 2: I thought I need to
> ADD_DEPENDENCIES(lib2 lib1)
> so that the order of the ADD_SUBDIRECTORY inclusion from the master
> cmakelists won't matter, but still if I change the order of inclusion, the
> lib1_include isn't set and I get the same error as above.

You don't need to use add_dependencies() between lib2 and lib1, cmake sees 
that by itself via the target_link_libraries() calls.
Still that doesn't change the order in which cmake reads the CMakeLists.txt, 
this is done straightforward, one by one, as they are used via 
add_subdirectory().

Alex


More information about the CMake mailing list