Search code examples
c++unit-testingbuildcmakegoogletest

How do I configure my CMake file to work with Google Test and CTest?


I am attempting to integrate the GTest framework into my project, but am not sure how to. I am using CMake to build it. I would ideally like to create a separate executable for running tests, and I would like the ability to choose to run tests on an individual module or the whole project. I'd also like it to work with CTest, but that isn't a priority. How would I set this up? My project is structured as follows:

3rdparty
   |--gtest
      |--include
         |--(gtest includes)
      |--lib
         |--libgtest.a
src
   |--module1
      |--file1.cpp
      |--file2.cpp
      |--CMakeLists.txt
   |--module2
      |--file3.cpp
      |--file4.cpp
      |--CMakeLists.txt
   |--CMakeLists.txt
include
   |--module1
      |--file1.hpp
      |--file2.hpp
   |--module2
      |--file3.hpp
      |--file4.hpp
test
   |--module1
       |--module1test.cpp
   |--module2
       |--module2test.cpp
CMakeLists.txt

This is my main CMakeLists.txt:

cmake_minimum_required(VERSION 3.1)
project(Aura)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

include_directories(include)
add_subdirectory(src)

set (run_src
    src/run.cpp
)

add_executable(aura ${run_src})
target_link_libraries(aura util)

Solution

  • You should add test executable such just like you added target aura and include gtest includes and link gtest library.

    Add following lines to your CMakeLists.txt:

    include_directories(3rdparty/gtest/include)
    link_directories(3rdparty/gtest/lib)
    
    add_executable(moduleTest1 moduleTest1.cpp)
    target_link_libraries(moduleTest1 gtest)
    

    If there are additional links with submodules you should link them as well. For example, if module1 needed, link with module1 too, e.g. target_link_libraries(moduleTest1 gtest module1)