C++ 如何使用Catch2和CMake添加单独的测试文件?

C++ 如何使用Catch2和CMake添加单独的测试文件?,c++,unit-testing,cmake,catch2,C++,Unit Testing,Cmake,Catch2,在中,他们只编译一个文件test.cpp,该文件可能包含所有测试。我想从包含#define CATCH\u CONFIG\u MAIN的文件中分离我的各个测试,如 如果我有一个文件test.cpp,其中包含\define CATCH\u CONFIG\u MAIN和一个单独的测试文件simple\u test.cpp,我已经成功地生成了一个可执行文件,其中包含simple\u test.cpp中的测试: find_package(Catch2 REQUIRED) add_executable(

在中,他们只编译一个文件
test.cpp
,该文件可能包含所有测试。我想从包含
#define CATCH\u CONFIG\u MAIN
的文件中分离我的各个测试,如

如果我有一个文件
test.cpp
,其中包含
\define CATCH\u CONFIG\u MAIN
和一个单独的测试文件
simple\u test.cpp
,我已经成功地生成了一个可执行文件,其中包含
simple\u test.cpp
中的测试:

find_package(Catch2 REQUIRED)

add_executable(tests test.cpp simple_test.cpp)
target_link_libraries(tests Catch2::Catch2)

include(CTest)
include(Catch)
catch_discover_tests(tests)

但是,这是生成可执行文件的一种可接受的方法吗?从不同的教程中,如果我有更多的测试,我应该能够创建一个测试源库,并将它们链接到
test.cpp
以生成可执行文件:

find_package(Catch2 REQUIRED)

add_library(test_sources simple_test.cpp another_test.cpp)
target_link_libraries(test_sources Catch2::Catch2)

add_executable(tests test.cpp)
target_link_libraries(tests test_sources)
target_link_libraries(tests Catch2::Catch2)

include(CTest)
include(Catch)
catch_discover_tests(tests)
但是当我尝试这个时,我得到了一个CMake警告
测试可执行文件。。。不包含任何测试

总而言之,我应该制作一个测试库吗?如果是,我如何使它包含我的测试。否则,将我的新test.cpp文件添加到
add\u executable
函数是否正确

如何使用Catch2和CMake添加单独的测试文件

使用对象库或使用
--Wl,--whole archive
。链接器在链接时从静态库中删除未引用的符号,因此测试不在最终可执行文件中


你能举个例子吗


你能举个例子吗?我不知道对象库是什么。它在我在你的问题中链接的链接中给出。。。CMake也有很好的在线文档,你可以在很多地方阅读关于对象库的内容。
find_package(Catch2 REQUIRED)

add_library(test_sources OBJECT simple_test.cpp another_test.cpp)
target_link_libraries(test_sources Catch2::Catch2)

add_executable(tests test.cpp)
target_link_libraries(tests test_sources)
target_link_libraries(tests Catch2::Catch2)

include(CTest)
include(Catch)
catch_discover_tests(tests)
find_package(Catch2 REQUIRED)

add_library(test_sources simple_test.cpp another_test.cpp)
target_link_libraries(test_sources Catch2::Catch2)

add_executable(tests test.cpp)
target_link_libraries(tests -Wl,--whole-archive test_sources -Wl,--no-whole-archive)
target_link_libraries(tests Catch2::Catch2)

include(CTest)
include(Catch)
catch_discover_tests(tests)