I have a project (with main.cpp
and some headers. Yes, it is a Catch2 test project as described in this blog). It compiles and runs.
My problem is: This project does nothing useful unless I add some more source files (my test cases). These source files use one header from the project and bring in some other dependencies as well (my library that I want to test).
The simple solution would be to copy this project, add the needed files and we are done.
Is there a better way? Currently with qmake I have the project defined in a catch.pri
file. By including this in an project I have everything for the qt and catch2 setup, and only have to define the files with the testcases by modifying the SOURCES
-Variable and the dependencies for the code to test.
Mapping this to CMake makes me ask questions:
First: when I include have a line like:
add_executable(tests main.cpp ${SOURCES})
Can I define SOURCES
in a later line?
Second and more important: Is it a good idea to do it this way?
Can I define SOURCES in a later line?
Yes, but not the way you've done it. You can define your executable target tests
with a few sources or no sources, but you can always append more sources later using the target_sources
command.
add_executable(tests main.cpp)
...
# Later in the CMake file (or in another CMake file added via 'add_subdirectory').
target_sources(tests PRIVATE
MyTestClass1.cpp
MyTestClass2.cpp
...
)
You can similarly add compilation flags to this tests
target later using target_compile_options
, and add dependencies to link to tests
using target_link_libraries
.