Adding headers to a library in CMake
c, c++, cmake, compilation
Solution
When you have a repetitive folder structure like this it is often handy to create a macro that automates this kind of stuff.
MACRO(ADD_SUBLIB libname)
#Compute required sources
file(GLOB sublib_sources "${libname}/src/*.cc")
#Create library
ADD_LIBRARY(${libname} SHARED ${sublib_sources})
#add this library's header folder to the global include set
INCLUDE_DIRECTORIES("${libname}/include")
ENDMACRO(ADD_SUBLIB)
#Call macro once per library
ADD_SUBLIB(lib1)
ADD_SUBLIB(lib2)
ADD_SUBLIB(lib3)
#Sample executable, who as a side effect of the macro calls will
# be able to include.
ADD_EXECUTABLE(myprog main.cpp)
#Link any of the created libraries
TARGET_LINK_LIBRARIES(myprog lib1 lib2 lib3)
Problem
I have quite a few libraries that look like this: ``` libs \lib1-- src \- include \lib2--src \- include ``` Where lib2 requires lib1. The way I have gotten by doing this is by doing something like this: ``` lib2/CMakeLists.txt: include ../lib1/include target_link_libraries(lib2 lib1) ``` How can I include the lib1 header/include files in the lib2 library? I am currently trying to do this, but during compilation I get errors that lib2 can't find the lib1 header files. ``` libs/CMakeLists.txt: file(GLOB lib1_src "lib1/src/*.cc" ) #header files file (GLOB lib1_h "lib1/include/*.h" ) file(GLOB lib2_src "lib2/src/*.cc" ) #header files file (GLOB lib2_h "lib2/include/*.h" ) add_library(lib1 ${lib1_src} ${lib1_h}) add_library(lib2 ${lib2_src} ${lib2_h}) target_link_libraries(lib2 lib1) ``` I can get it to work by adding `include_directories(lib1/include)` to the `libs/CMakeLists.txt` but I'm getting to the point where one library requires 3 others, which each requires 3 others, etc. and it's getting pretty tedious.