CMake
Table of contents
Important functions
You will need to modify parts of CMakeLists.txt
to work for your project. You should familiarize yourself with the following important functions:
-
add_library
(doc)- Defines a library with the specified source files.
-
add_executable
(doc)- Defines an executable with the specified source files.
-
target_link_libraries
(doc)- Defines library dependencies for executables. Used to link executables to libraries. In addition to your defined libraries, you may need to link with:
Boost::log
Boost::signals
Boost::system
gtest_main
Threads::Threads
- Defines library dependencies for executables. Used to link executables to libraries. In addition to your defined libraries, you may need to link with:
-
gtest_discover_tests
(doc)- Defines tests for the given
gtest
test executable.
- Defines tests for the given
-
add_test
(doc)- Defines a manual test with a given command. Useful for non-gtest non-C++ tests (like integration test scripts).
-
generate_coverage_report
- Creates a code coverage report. See
CodeCoverageReportConfig.cmake
source for documentation.
- Creates a code coverage report. See
Out of source builds
CMake generates numerous output files, even before performing a build. In order to keep all of CMake’s output isolated, you should perform out-of-source builds. In short, this means creating a build
directory, and running cmake
from that directory, referencing the directory containing CMakeLists.txt
(usually the parent directory):
$ mkdir build
$ cd build
$ cmake ..
$ make
If you need to clean out all the generated build files, you can simply delete the build
directory and start over. Additionally, if you want to run cmake
with multiple configurations (e.g. different sets of -D
defines), then you can create multiple build directories (or sub-directories) from which you can run different cmake
configurations.
Running tests
CMake includes the ctest
program that allows you to build and run tests (assuming cmake
has already been run). CMake also creates a test
target in the generated Makefile
that wraps ctest
:
$ ctest
or
$ make test
To see more test output, run ctest with the -V
flag:
$ ctest -V
or
$ make test ARGS=-V
Test code coverage reports
The project templates include a CMake macro for generating code coverage reports with gcovr
. A code coverage build of a binary includes extra code to generate output files showing which lines and branches were executed. To avoid interference with your regular build, perform an out-of-source build in a different directory (e.g. build_coverage
instead of build
). For example, to generate code coverage reports for the CMakeLists.txt
generated from our project templates:
$ mkdir build_coverage
$ cd build_coverage
$ cmake -DCMAKE_BUILD_TYPE=Coverage ..
$ make coverage
This will create an HTML report in ${REPO}/build_coverage/report/index.html
that you can view in your browser.