find_package does not find GTest which is part of

2020-07-22 17:41发布

问题:

I want to find GTest via:

find_package(GTest REQUIRED)

But it is not found:

Error:Could NOT find GTest (missing: GTEST_LIBRARY GTEST_INCLUDE_DIR GTEST_MAIN_LIBRARY)

I know from this link that GTest should be distributed via standard CMake.

Can you tell me what I did wrong?

回答1:

If you're on Ubuntu, you should read /usr/share/doc/libgtest-dev/README.Debian. It says:

The Google C++ Testing Framework uses conditional compilation for some things. Because of the C++ "One Definition Rule", gtest must be compiled with exactly the same flags as your C++ code under test. Because this is hard to manage, upstream no longer recommends using precompiled libraries

So you should compile and install your own version of the gtest library with the exactly same Compiler Options, and set the GTEST_LIBRARY or GTEST_ROOT variable accordingly.

For example, I did the following:

$ mkdir -p ExternalLibs/gTest
$ cd ExternalLibs/gTest
$ cmake /usr/src/gtest
$ make

Then I added the following lines in my CMakeLists.txt:

set (GTEST_ROOT ${CMAKE_SOURCE_DIR}/ExternalLibs/gTest)
find_package(GTest REQUIRED)


回答2:

If you have gtest installed you can just do:

add_subdirectory("/usr/src/gtest" ${CMAKE_BINARY_DIR}/gtest)
enable_testing()
include_directories(${GTEST_INCLUDE_DIRS})
add_executable(test test.cpp)
target_link_libraries(test gtest gtest_main)
add_test(AllTests test)


回答3:

find_package does not look in CMake's installation directory. It only evaluates the PATH and CMAKE_PREFIX_VARIABLES. Just add the path to CMake's GTest to the latter variable, clear your CMake cache and re-run CMake.