Search code examples
c++cmakecatch2

Unable to compile simple project structure (uses catch2 library) with cmake


I have a very simple project structure and I'm not being able to compile with CMake. I've tried to read documentation about CMake or tutorials, but I can't get it to work.

There's a similar question, but even trying what the answers suggested I can't get it to work.

You can see my full code here

But the relevant CMakeLists are:

root level:

cmake_minimum_required(VERSION 3.5)

find_package(Catch2 REQUIRED)

project(majorityQueries LANGUAGES CXX VERSION 0.0.1)

include_directories(include)

add_subdirectory(src)
add_subdirectory(tests)

file(GLOB SOURCES "*.cpp")

src:

add_library(fact factorial.cpp)

tests:

add_executable(test test_factorial.cpp)

target_link_libraries(test Catch2::Catch2)

But basically I have a test_factorial.cpp file, that includes the header factorial.hpp (inside an include directory) and therefore should know about the existence of the Factorial(int) function, but it says it undefined.

What I try is:

cd build/
cmake ..
make

I expected the make to work, instead I get:

Undefined symbols for architecture x86_64:
  "Factorial(int)", referenced from:
      ____C_A_T_C_H____T_E_S_T____0() in test_factorial.cpp.o
  "Catch::NameAndTags::NameAndTags(Catch::StringRef const&, Catch::StringRef const&)", referenced from:
      ___cxx_global_var_init in test_factorial.cpp.o
  "Catch::StringMaker<int, void>::convert(int)", referenced from:
      std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > Catch::Detail::stringify<int>(int const&) in test_factorial.cpp.o (...)

Solution

  • As i already wrote in my comment, add the source file test_main.cpp and library fact to ./tests/CMakeLists.txt.

    add_executable(test test_main.cpp test_factorial.cpp)
    target_link_libraries(test fact Catch2::Catch2)