首页 > 解决方案 > 如何在一个 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.cppmain.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 NORMALand cmake TEST

标签: c++unit-testingc++11cmake

解决方案


正如评论中已经指出的那样,通过add_executable使用多个目标。以下CMakeLists.txt将生成两个目标,生成可执行文件studentstudent-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)

推荐阅读