Using FetchContent()
to integrate gtest into project in cmake seems to be missing the relevant include path for gtest/gtest.h
Building on linux works fine with gcc
cmake ..
cmake --build .
But building on windows with msvc
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Auxiliary\Build\vcvarsall" x86
cmake -G "Ninja" ..
cmake --build .
Results in:
Cannot open include file: 'gtest/gtest.h': No such file or directory
fatal error C1083: Cannot open include file: 'gtest/internal/gtest-port.h
Main cmake:
cmake_minimum_required(VERSION 3.9)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(VERBOSE ON)
project(test)
option(UNIT_TESTS "Build the unit tests" ON)
if(UNIT_TESTS)
enable_testing()
add_subdirectory(test)
endif()
Here is relevant test cmake:
include(FetchContent)
FetchContent_Declare(gtest
GIT_REPOSITORY https://github.com/google/googletest
GIT_TAG release-1.11.0)
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(gtest)
set(project "test_example")
add_executable(${project} example.cpp)
target_link_libraries(${project} gtest_main)
include(GoogleTest)
gtest_discover_tests(${project})
Update
Just tested on windows using clang compiler and it works, so seems specific to msvc.
Amazingly changing FetchContent_Declare(gtest
to FetchContent_Declare(googletest
fixed this issue. I found this page https://github.com/google/googletest/issues/2457 which seems to be exact same issue as I had.
I just ran into the same problem and found a way to solve it. Although this could be considered a hack.
The problem is that FetchContent_MakeAvailable
creates gtest_SOURCE_DIR
, which points to the root directory of the fetched dependency. The subprojects googletest/googlemock also use gtest_SOURCE_DIR
for adding the include paths (which should be ${gtest_SOURCE_DIR}/googletest
now). This name conflict results in missing include directories for the downstream project.
You can fix it by by replacing gtest_SOURCE_DIR
manually. This requires using FetchContent_Populate
and add_subdirectory
.
FetchContent_Declare(
gtest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG v1.12.0
GIT_SHALLOW ON
)
FetchContent_GetProperties(gtest)
if(NOT gtest_POPULATED)
FetchContent_Populate(gtest)
set(TEMP_SOURCE_DIR ${gtest_SOURCE_DIR})
set(gtest_SOURCE_DIR ${gtest_SOURCE_DIR}/googletest)
add_subdirectory(${TEMP_SOURCE_DIR} ${gtest_BINARY_DIR})
endif()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.