【问题标题】:How to integrate g++ and gtest in one cmake file如何在一个 cmake 文件中集成 g++ 和 gtest
【发布时间】:2019-12-09 21:21:06
【问题描述】:

我正在尝试将正常编译和带有 gtest 的单元测试集成到一个 cmake 文件中,但我不知道如何实现这一点。这是我的项目:

|---include
|     |---Student.h
|
|---src
|    |---Student.cpp
|    |---main.cpp
|
|---unittest
|      |---TestStudent.cpp
|
|---CMakeLists.txt   # how to write this file?

所以Student.hStudent.cppmain.cpp是源代码,TestStudent.cpp是测试代码,其中包括gtest/gtest.h和一个main函数,这里是:

#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 NORMALcmake TEST

【问题讨论】:

  • 您添加两个可执行目标,每个可执行文件一个。然后 CMake 将使用这两个目标创建一个 Makefile(或项目),以便您可以分别构建它们。
  • @Someprogrammerdude 你能给我看一个非常简单的例子吗?
  • 你知道 CMake add_exectuable 命令吗?您可以在单个 CMakeLists.txt 中拥有任意数量的 add_executable 命令。

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


【解决方案1】:

正如 cmets 中已经指出的那样,通过 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)

【讨论】:

    猜你喜欢
    • 2016-11-04
    • 2018-10-02
    • 1970-01-01
    • 2012-01-20
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 2017-11-27
    相关资源
    最近更新 更多