Blog Series Tags

CMake add_library

In the last post we built an executable from a source file and a header only library. However, sometimes we need to build shared library binaries that can be linked into an executable. This is fairly simple with CMake. Instead of using add_executable like the last time we now simply need to use add_library like so:

# Sources 
file(GLOB Library_SOURCES *.cpp)
file(GLOB Library_HEADER *.hpp) 

# Executable
add_library(LibProject ${Library_SOURCES} ${Library_HEADERS})

CMake will now get the build system that you choose to create a shared library that can be linked into an executable one. You would end up with .lib files with Visual Studio and typically .a files with Unix make. Note that the name Library_SOURCES is chosen for clarities sake. The variable can be named anything.

CMake is explicitly hierarchical. That is, given a structure of CMakeLists.txt files like the following:

[1] src\CMakeLists.txt
[2] src\LibProject\CMakeLists.txt
[3] src\ExeProject\CMakeLists.txt

CMake will only execute [1] if you give src as the source directory during build file generation - unless you specify that [2] and [3] should also be included inside your [1] CMakeLists.txt project. You do that like so:

add_subdirectory(LibProject)
add_subdirectory(ExeProject)

Order is important here. If you add the Lib project before the Exe project, then you can do the following during your creation of the executable to get CMake to link in the library file.

#Sources
file(GLOB Executable_SOURCES *.cpp)
file(GLOB Executable_HEADERS *.hpp)

add_executable(ExeProject ${Executable_SOURCES} ${Executable_HEADERS}) 

# Link in the library 
target_link_libraries(ExeProject LibProject)

You can link in multiple Library files (as long as they have been added before in the same CMake project).

This is a post in the CMake series.