...
After the source and test code are ready, the project can be built and compiled. At the top of the project's folder structure, add CMakeListCMakeLists.txt. The contents of the file are listed below:
...
This is a simple setup for CMake builds, however it's important to get it right. At the beginning there are very basic lines that tell you the minimum CMake version required, the project name and the C++ standard used. Then the src directory is included and added. Next comes a very important line that enables testing and finally adds the tst directory as a subdirectory.
Then, in each subdirectory, another CMakeLists.txt file must be added accordingly. At first the ./src/CMakeLists.txt:
Code Block | ||||
---|---|---|---|---|
| ||||
add_library(src operations.cpp operations.h)
add_executable(
src_main main.cpp operations.cpp
)
target_sources(src
PRIVATE
main.cpp
PUBLIC
main.h
)
target_include_directories(src
PUBLIC
.
)
|
Last but not least, the ./tst/CMakeLists.txt file which is a bit more elaborate and needs some explanation:
Code Block | ||||
---|---|---|---|---|
| ||||
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/4ec4cd23f486bf70efcc5d2caa40f24368f752e3.zip
)
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
add_executable(
tests
run_tests.cpp
test_operations.cpp
)
target_link_libraries(tests
PRIVATE
src
gtest_main
)
# Auto-discovery of the tests
include(GoogleTest)
gtest_discover_tests(tests
PROPERTIES
LABELS "unit"
DISCOVERY_TIMEOUT
240) |
Most importantly, it is the FetchContent function that downloads the GoogleTesting framework when building the project. It is recommended that you use the exact same URL listed above for the purpose of this tutorial, however in future use this URL may be changed to a different version available in the googletest repository.