Advanced CMake Features
There are several advanced features of the CMake build system that may be of use on projects as they get larger. This is far from a comprehensive list, and information related to unlisted tasks may be found on official CMake documentation.
Contents
Background
This page is written with the assumption that the project being worked on has been created using the oe_init_project script or using the EMAC New C/C++ Project in Qt Creator.
Advanced CMake Features
Adding External Library Files
To add an external library to the CMake project, more changes will need to be made to the CMakeLists.txt
file. Please refer to the code sample below. In this example, the ImageMagick library will be linked into the project.
- The library directory must be included using the
INCLUDE_DIRECTORIES()
function. This function must be before theADD_EXECUTABLE()
function. - Use the
TARGET_LINK_LIBRARIES()
function to link the desired library to the target binary. This function must be after theADD_EXECUTABLE()
function.
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR} "/usr/include/ImageMagick")
ADD_EXECUTABLE(main main.cpp) # This should be here by default
TARGET_LINK_LIBRARIES(main MagickWand)
Adding Additional C/C++ Sourrce Files as Libraries
Adding additional source files is accomplished similarly to adding external library files. See above.
- All included files must be included in the
SOURCES
list. - All header files must be included in the
HEADER_FILES
list. - Each C/C++ source file must be added as a library before adding the executable.
- Add the executable, including the
${HEADER_FILES}
. - Link the target libraries to the executable.
SET(SOURCES
${PROJECT_SOURCE_DIR}/include/tools.cpp
${PROJECT_SOURCE_DIR}/include/funcs.cpp
${PROJECT_SOURCE_DIR}/include/tools.h
${PROJECT_SOURCE_DIR}/include/funcs.h
)
SET(HEADER_FILES
${PROJECT_SOURCE_DIR}/include/tools.h
${PROJECT_SOURCE_DIR}/include/funcs.h
)
ADD_LIBRARY(tools include/tools.cpp ${HEADER_FILES})
ADD_LIBRARY(funcs include/funcs.cpp ${HEADER_FILES})
ADD_EXECUTABLE(main main.cpp ${HEADER_FILES})
TARGET_LINK_LIBRARIES(main tools funcs)
Conclusion
As stated previously, this guide is just a small list of common task requests. Please refer to official or other third-party documentation for more information.