[CMake] Best practice for static libraries and include files

Alessandro Saccoia alessandro.saccoia at gmail.com
Fri Mar 8 08:19:54 EST 2013


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?

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.

what is this the only way to deal with include files in this scenario?
Thank you
Alessandro








More information about the CMake mailing list