m4l490n
m4l490n

Reputation: 1692

Why is main not found when building a project that includes gtest with cmake?

I have a very small project to which I created some unit testing with GTest. To build it, I'm using CMake. It compiles just fine, but it's giving me the error shown below. I include all make output just in case.

Scanning dependencies of target trace
[ 33%] Building C object CMakeFiles/trace.dir/trace/system_trace.c.o
[ 33%] Built target trace
Scanning dependencies of target data-test
[ 66%] Building CXX object CMakeFiles/data-    test.dir/data_testsuite.cpp.o
[100%] Linking CXX executable data-test
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
CMakeFiles/data-test.dir/build.make:86: recipe for target 'data-test'     failed
make[2]: *** [data-test] Error 1
CMakeFiles/Makefile2:72: recipe for target 'CMakeFiles/data-test.dir/all' failed
make[1]: *** [CMakeFiles/data-test.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

And I have no idea why is not finding main. Main is part of GTest which I'm including as it can be seen on the CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)

set (CMAKE_CXX_STANDARD 11)

project(data-test C CXX)

set(CMAKE_C_FLAGS_DEBUG   "-g3 -Og -Wall")
set(CMAKE_CXX_FLAGS_DEBUG "-g3 -Og -Wall")

set(CMAKE_C_FLAGS_RELEASE   "-g0 -O3 -Wall")
set(CMAKE_CXX_FLAGS_RELEASE "-g0 -O3 -Wall")

include(GoogleTest)

set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
find_package(Threads REQUIRED)

find_package(GTest REQUIRED)

include_directories(cfg)
include_directories(system)
include_directories(system/include)

include(trace/CMakeLists.txt)

add_executable(data-test
    $<TARGET_OBJECTS:trace>
    data_testsuite.cpp
)

target_link_libraries(data-test Threads::Threads GTest::GTest)

gtest_discover_tests(data-test)

And as you can see from the make command output, it is compiling just fine.

Do you know what is going on?

Upvotes: 0

Views: 1304

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 66118

The libraries defined by the target GTest::Gtest doesn't contain main function definition. For obtain definition of main you need link with GTest::Main. This is written in documentation.

target_link_libraries(data-test Threads::Threads GTest::Main)

Upvotes: 1

Related Questions