c++ - 如何在一个 cmake 文件中集成 g++ 和 gtest
问题描述
我正在尝试将正常编译和带有 gtest 的单元测试集成到一个 cmake 文件中,但我不知道如何实现这一点。这是我的项目:
|---include
| |---Student.h
|
|---src
| |---Student.cpp
| |---main.cpp
|
|---unittest
| |---TestStudent.cpp
|
|---CMakeLists.txt # how to write this file?
所以, Student.h
,Student.cpp
和main.cpp
是源代码,TestStudent.cpp
是测试代码, 其中包括gtest/gtest.h
一个主函数, 这里是:
#include "gtest/gtest.h"
#include "Student.h"
class TestStudent : public ::testing::Test
{
protected:
Student *ps;
void SetUp() override
{
ps = new Student(2, "toto");
}
void TearDown() override
{
delete ps;
}
};
TEST_F(TestStudent, ID)
{
EXPECT_TRUE(ps->GetID() == 2);
EXPECT_TRUE(ps->GetName() == "toto");
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
现在,如果我想编译源代码,我需要运行g++ -std=c++11 Student.cpp main.cpp -o a.out
,而如果我想编译测试代码,我需要运行g++ -std=c++11 TestStudent.cpp Student.cpp -lgtest -lpthread -o test.out
。
那么,我怎样才能编写CMakeLists.txt
允许我编译不同的目标,例如cmake NORMAL
and cmake TEST
?
解决方案
正如评论中已经指出的那样,通过add_executable使用多个目标。以下CMakeLists.txt
将生成两个目标,生成可执行文件student
和student-test
.
如果您不关心CTest,可以省略最后三行。
cmake_minimum_required(VERSION 3.9)
project(Student CXX)
set(CMAKE_CXX_STANDARD 11)
set(SOURCES src/Student.cpp)
set(INCLUDES include)
find_package(GTest REQUIRED)
add_executable(student src/main.cpp ${SOURCES})
target_include_directories(student PRIVATE ${INCLUDES})
add_executable(student-test unittest/TestStudent.cpp ${SOURCES})
target_include_directories(student-test PRIVATE ${INCLUDES})
target_link_libraries(student-test GTest::GTest GTest::Main)
enable_testing()
include(GoogleTest)
gtest_add_tests(TARGET student-test AUTO)
推荐阅读
- appium - 如何在 MAC 中更新 WebDriverAgent (WDA)?
- plot - 是否可以在 xmgrace 中旋转图例框?
- python - 如何在 SymPy 中求解以下模式方程,例如 (x-1)**2+y**2=0?
- postgresql - 在保持数据完整性的同时将数据从 Postgres (RDS) 复制到 AWS Redshift 的最有效方法是什么
- css - 仅在使用 Vue 悬停时显示截断的文本
- python - 我想加入两个数据框列但没有得到想要的输出
- javascript - 如何使用 Javascript 对对象进行深度过滤
- java - IntelliJ Idea 将 bean 标记为无法为参数自动装配错误,但代码有效
- ios - 再次触摸时如何删除scnplane?
- angular - PrimeNg树表如何区分一个页面中的两个不同的表。?