1

I'm working with C++ on Ubuntu and trying to make two targets with the help of cmake, one is the normal exe and the other is to run the unit-test. here is my project:

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

Now the CmakeLists.txt is like this:

cmake_minimum_required(VERSION 3.9)
project(Student CXX)

set(CMAKE_CXX_COMPILER g++)
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})
target_compile_options(student PRIVATE -std=c++11 -g)

add_executable(student-test unittest/TestStudent.cpp ${SOURCES})
target_include_directories(student-test PRIVATE ${INCLUDES})
target_compile_options(student-test PRIVATE -std=c++11 -g -O0)
target_link_libraries(student-test -lgtest -lpthread -fprofile-arcs -ftest-coverage)

enable_testing()
include(GoogleTest)
gtest_add_tests(TARGET student-test AUTO)

So, after executing mkdir build && cd build && cmake .. && make, two executable files are generated: student and student-test. However, when I execute ./student-test, the raw coverage file isn't generated. But if I compile it with the pure command: g++ -std=c++11 TestStudent.cpp ../src/Student.cpp -I ../include/ -lgtest -lpthread -fprofile-arcs -ftest-coverage -g -O0 -o student-test, it works without any problem, meaning that ./student-test could generate the relative raw coverage files.

Why can't the CmakeLists.txt do the same thing?

Yves
  • 11,597
  • 17
  • 83
  • 180
  • 1
    Why is `-ftest-coverage` in `target_link_libraries` (and not a compiler flag)? I believe `-coverage` needs to be added to `CFLAGS` and `CXXFLAGS`. The compiler will do the right thing if it drives link. – jww Aug 02 '19 at 06:38
  • @jww So do you mean I need to add `-coverage` into `target_compile_options(student-test PRIVATE -std=c++11 -g -O0 -coverage)`? I've tried but it doesn't work either. – Yves Aug 02 '19 at 06:45
  • @Moia Sorry, I still don't know what I could do. – Yves Aug 02 '19 at 07:16

0 Answers0