来自不同文件夹的 CMake 测试源

ash*_*agi 5 c++ cmake googletest ctest

我开始使用 CMake 来使用 Qt 创建一个项目,并使用 Google Test 对其进行测试。此刻,我成功地找到了编译和链接所有所需库的方法。但是,我找不到将源链接到具有以下项目结构的测试文件的方法:

root
|
+-- CMakeLists.txt
+-- src
| |
| +-- CMakeLists.txt
| +-- MyClass.h
| +-- MyClass.cpp
|
+-- test
| |
| +-- CMakeLists.txt
| +-- MyClassTest.cpp
|
+-- lib
  |
  +-- gtest-1.6.0
    |
    +-- CMakeLists.txt
Run Code Online (Sandbox Code Playgroud)

根 CMakeLists.txt 包含 gtest、src 和 test 文件夹的 add_subdirectory。我已成功编译并运行“Hello world”应用程序和简单的 EXPECT_TRUE(true) 测试,以检查每个部分是否正确编译。不幸的是,我找不到将我的源文件包含到测试中的方法。以下项目结构是否可行?

PS我知道可以将我的源代码编译为库并将其链接到测试,但我不喜欢这种方法,因为它更适合集成测试,而不是单元测试......

编辑:将类名添加到树中

Kik*_*ohs 2

您可以在根 CMakeLists.txt 级别添加全局变量:

set(ALL_SRCS CACHE INTERNAL "mydescription" FORCE)
Run Code Online (Sandbox Code Playgroud)

在第一个 add_subdirectory(src) 中,您可以执行以下操作:

set(ALL_SRCS ${ALL_SRCS} blabla.cpp CACHE INTERNAL "description")
Run Code Online (Sandbox Code Playgroud)

在 add_subdirectory(test) 中,您继续:

set(ALL_SRCS ${ALL_SRCS} bla_test.cpp CACHE INTERNAL "description")
Run Code Online (Sandbox Code Playgroud)

然后,您可以对所有源文件执行 add_executable 或库或其他操作。

编辑:在 CMake 中添加全局变量的技巧。