Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build gtest within project and use find_package(GTest) and GTEST_ADD_TESTS in cmake?

I want to use gtest within a CMake project. Previously, I had built gtest and copied the headers and libraries into a location where they could be found in order to overcome the lack of an Ubuntu package to provide the same.

The approach recommended by the gtest developers is to build gtest inside the project that is using it.

However, I would also like to use the functions gtest_add_tests and gtest_discover_tests, which are defined in CMake's GoogleTest module.

But find_package(GTest REQUIRED) fails because the library hasn't been built yet:

Could NOT find GTest (missing: GTEST_LIBRARY GTEST_MAIN_LIBRARY)

So it seems like it has to be a two stage process, and there is no way to guarantee compliance with the 'One-Definition Rule'. Do I need to write a custom FindGTest.cmake that defines the functions but doesn't look for the libraries, so that they will only become available after cmake completes and make builds them?

like image 322
Lucas W Avatar asked Oct 21 '22 04:10

Lucas W


1 Answers

You might consider using External Projects.

http://www.kitware.com/media/html/BuildingExternalProjectsWithCMake2.8.html

You could use it roughly like the following (from my code that does the same thing, versions may vary, etc):

set(GTest_version 1.6.0)
set(GTest_url "http://googletest.googlecode.com/files/gtest-${GTest_version}.zip")
set(GTest_md5 "4577b49f2973c90bf9ba69aa8166b786")
set(GTest_BUILD_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/build")
set(GTest_BUILD_INSTALL_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/install")
set(GTest_DOWNLOAD_DIR "${CMAKE_CURRENT_SOURCE_DIR}/Downloads")

ExternalProject_Add(GTest
  URL ${GTest_url}
  URL_MD5 ${GTest_md5}
  PREFIX  ${GTest_BUILD_PREFIX}
  DOWNLOAD_DIR ${GTest_DOWNLOAD_DIR}
  CMAKE_GENERATOR ${gen}
  CMAKE_ARGS
    -DBUILD_SHARED_LIBS:BOOL=ON
    -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE}
    -DCMAKE_INSTALL_PREFIX:PATH=${GTest_BUILD_INSTALL_PREFIX}
    -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}
)

set(GTEST_ROOT ${GTest_BUILD_INSTALL_PREFIX} CACHE STRING "")
like image 125
StAlphonzo Avatar answered Oct 23 '22 00:10

StAlphonzo