Yves
Yves

Reputation: 12431

How to integrate g++ and gtest in one cmake file

I'm trying to integrate a normal compilation and a unit-test with gtest into one cmake file, but I don't know how to achieve this. Here is my project:

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

So, Student.h, Student.cpp and main.cpp is the source code, TestStudent.cpp is the test code, which includes gtest/gtest.h and a main function, here it is:

#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();
}

Now, if I want to compile the source code, I need to run g++ -std=c++11 Student.cpp main.cpp -o a.out, whereas if I want to compile the test code, I need to run g++ -std=c++11 TestStudent.cpp Student.cpp -lgtest -lpthread -o test.out.

So, how could I write the CMakeLists.txt to allow me to compile the different targets, such as cmake NORMAL and cmake TEST?

Upvotes: 2

Views: 419

Answers (1)

Lasall
Lasall

Reputation: 480

As already pointed out in the comments use multiple targets via add_executable. The following CMakeLists.txt will produce two targets generating the executables student and student-test.

The last three lines can be omitted if you don't care about 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)

Upvotes: 4

Related Questions