jeudi 1 août 2019

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?

Aucun commentaire:

Enregistrer un commentaire