GTest Submodule

Note: There is a better way to do this described here.

If you’ve ever tried apt-get or brew to try to install gtest, you are probably familiar with the fact that gtest is not “recommend” for global install on your system. As an alternative, the recommendation is that you make it part of your project. The process for making gtest part of your project, however, is not well documented, at least for modern git projects. What follows is the procedure I used to do so.

Now that gtest is a git repository, you’ll want to check it out as a submodule for your project. The command is

$ git submodule add https://github.com/google/googletest.git
$ cd googletest
$ git checkout release-1.7.0
$ cd ..
$ git add googletest

Here, we’ve added googletest as a submodule, then changed the reference to the 1.7.0 tag (assuming you don’t want some random commit in the middle of a release cycle).

Now, to set up cmake, add the following to your main CMakeLists.txt right before your add_subdirectory(tests) line, so that it looks like this:

add_subdirectory(googletest)
enable_testing()
add_subdirectory(tests)

Now, your tests/CMakeLists.txt should look something like this:

include_directories(SYSTEM
    ${gtest_SOURCE_DIR}
    ${gtest_SOURCE_DIR}/include)

file(GLOB_RECURSE test_cases *.cpp)
foreach(case_file ${test_cases})
    get_filename_component( case_name ${case_file} NAME_WE )
    set (case_name test_${case_name})
    add_executable(${case_name} ${case_file})
    target_link_libraries(${case_name} ${PROJECT_NAME}
                          ${LINK_LIBS} gtest_main pthread)
    add_test(NAME ${case_name}
             COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${case_name}
             WORKING_DIRECTORY
             ${PROJECT_BINARY_DIR})
endforeach()

Of course, you may need to edit this a little, like if you don’t want to have test_ appended to each test binary name.

comments powered by Disqus