How to use CMake with Catch2?

Many problems here:

add_executable(fact fact.cpp)

The call should be using add_library (You could also specify STATIC or SHARED), since you are only defining a factorial function, not an executable with a main function.

add_executable(fact fact.cpp)

The file should be test_fact.cpp and the target should have a different name to avoid conflict with the previous library you created. Also, your fact.cpp doesn't include fact.hpp. Last but not least, instead of doing target_include_directories, just write the following in your top-level CMakeLists.txt:

include_directories(include)

Now, all subdirectories should be able to access the header files. Beware that this removes control of the scoping of the header files (PRIVATE vs PUBLIC vs INTERFACE) and allows all subdirectories to access the header files. If you want to restrict this behavior, then use target_include_direcories for all targets (Your library and the test executable). For this example, since everything needs to access the header files, there is no problem with the statement above.

More problems:

project(factorial)
cmake_minimum_required(VERSION 2.8.12)

Either switch the order of these statements, or remove both of them. (You only need them in your top level CMake file)


If you look at the CMake documentation, the PROJECT_SOURCE_DIR variable is define as that:

Top level source directory for the current project.

This is the source directory of the most recent project() command.

Since you called project many times, that variable will constantly change. I would suggest you to remove your project directive, or to use CMAKE_SOURCE_DIR, which always point to the source directory of the whole project.


As a side note, I suggest to use set(CMAKE_CXX_STANDARD 11) instead of add_definition