Introduction
There are several articles that show how important software testing is. I recently learned about writing tests for C/C++ projects using CMake. I googled about various frameworks that people use for testing their projects, like googletest, etc., but since CMake is very widely used and trusted, I decided to use it to write tests. I found out that testing is integrated inside CMake as
CTest
.The CMakeLists.txt file
In case of CMake, the most important element is the
CMakeLists.txt
file, that contains all the build instructions related to the project.Simple version
Let’s see how a simple
CMakeLists.txt
file looks like:cmake_minimum_required(VERSION 3.9)project(ecsh)add_executable(ecsh src/main.c src/utils.c src/utils.h)set_property(TARGET ecsh PROPERTY C_STANDARD 99)set_property(TARGET ecsh_main_test PROPERTY C_STANDARD 99)set_property(TARGET ecsh_util_tests PROPERTY C_STANDARD 99)
Breaking it down
cmake_minimum_required
: The minimum version of cmake required to build this project.
project
: name of the project.
add_executable
: adds an executible that is created with the name ofecsh
here and contains the source code files:src/main.c
,src/utils.c
,src/utils.h
.
set_property
: You can add flags for the compiler to build your files.
CMake with testing
Now, let’s add some tests to our project by adding the code below:
enable_testing()# test that checks if the shell starts properlyset(COMMON_TEST_EXE_NAME ecsh_main_test)add_executable(${COMMON_TEST_EXE_NAME} tests/main_test.c)add_test(NAME "ecsh_main_test" COMMAND ${COMMON_TEST_EXE_NAME})# test that checks the utility functions that are implementedset(UTIL_TEST_EXE_NAME ecsh_util_tests)add_executable(${UTIL_TEST_EXE_NAME} tests/utils_test.c)add_test(NAME "ecsh_util_tests" COMMAND ${UTIL_TEST_EXE_NAME})
Breaking it down
enable_testing()
: This statement let’s us add tests to the file. After adding this, any tests that are defined in ourCMakeLists.txt
will be built and run using the commandmake test
after runningcmake . && make
.
add_test
: this lets you add an executable to the tests and run later.
Conclusion
This was a very simple example of using CMake to write tests for C/C++ projects. You can take a look at the project
ecsh
here for more details about the structure: github.com/manparvesh/ecsh