App2015
App2015

Reputation: 993

CMake configuration for multiple test files

I'm running into following error. Basically I've two test .c files, how can I've them run both independently? Each one having it's own main function?

duplicate symbol _main in:

CMakeFiles/Tests.dir/test.c.o

CMakeFiles/Tests.dir/test2.c.o

Root CMakeLists.txt

cmake_minimum_required(VERSION 3.9)
project(Polymorphism)

set(CMAKE_C_STANDARD 99)

add_subdirectory(src)
add_subdirectory(test)

src/CMakeLists.txt

add_library(Polymorphism person.c employee.c)
target_include_directories(Polymorphism PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

test/CMakeLists.txt

add_executable(Tests test.c test2.c)
target_link_libraries(Tests Polymorphism)

test/test.c

void main() {
    // some tests
}

test/test2.c

void main() {
   // some tests
}

Upvotes: 4

Views: 5033

Answers (1)

Arnav Borborah
Arnav Borborah

Reputation: 11807

This is actually quite simple to solve. CMake allows you to create multiple executables (These can have their own main function) and also contains a function add_test used to bind these to tests.

So, given that you have files test.c and test2.c, each with their own main function:

add_executable(test1 test.c)
add_executable(test2 test2.c)

add_test(NAME t1 COMMAND test1)
add_test(NAME t2 COMMAND test2)

Now, you can run the commands make test or ctest, which will register two separate tests and run them as such.

Upvotes: 4

Related Questions