CMake错误:无法找到软件包GTest

时间:2020-07-21 09:01:13

标签: c++ cmake googletest

我正在使用CMake开发C / C ++应用程序。我想在我的项目中使用GTest进行单元测试。为此,我决定将GTest用作存储库中的git子模块。

我的目录层次结构如下:

/
--include
--lib
  --GoogleTest
--src
--Tests

GoogleTest中的lib子目录包含其官方存储库中GTest的源代码。

但是我无法使用它来测试我的来源。我的存储库根目录中的CMakeLists.txt文件如下:

OPTION (BUILD_UNIT_TESTS "Build unit tests" ON)

if (BUILD_UNIT_TESTS)
    enable_testing ()
    find_package (GTest REQUIRED)
    add_subdirectory (Tests)
endif ()

但是我收到错误消息:

错误:找不到GTest(丢失:GTEST_LIBRARY GTEST_INCLUDE_DIR GTEST_MAIN_LIBRARY)

当我搜索此内容时,有许多与我相似的问题,但没有一个解决我的问题。而且他们的手册非常有限,没有正确说明其用法。

CMake能够成功构建目标GTest,但是当我尝试将其用作外部软件包时无法识别它。

1 个答案:

答案 0 :(得分:1)

您不必手动下载Gtest git。只需将以下行添加到您的CMakeLists.txt

# -------- GOOGLE TEST ----------
# Download and unpack googletest at configure time
configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
        RESULT_VARIABLE result
        WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
if(result)
    message(FATAL_ERROR "CMake step for googletest failed: ${result}")
endif()
execute_process(COMMAND ${CMAKE_COMMAND} --build .
        RESULT_VARIABLE result
        WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
if(result)
    message(FATAL_ERROR "Build step for googletest failed: ${result}")
endif()

# Prevent overriding the parent project's compiler/linker
# settings on Windows
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)

# Add googletest directly to our build. This defines
# the gtest and gtest_main targets.
add_subdirectory(${CMAKE_CURRENT_BINARY_DIR}/googletest-src
        ${CMAKE_CURRENT_BINARY_DIR}/googletest-build
        EXCLUDE_FROM_ALL)

# The gtest/gtest_main targets carry header search path
# dependencies automatically when using CMake 2.8.11 or
# later. Otherwise we have to add them here ourselves.
if (CMAKE_VERSION VERSION_LESS 2.8.11)
    include_directories("${gtest_SOURCE_DIR}/include")
endif()
# -------------------------------------------------------------------------
enable_testing()
include_directories("${gtest_SOURCE_DIR}/include")

并将以下行添加到您的CMakeLists.txt.in文件所在的同一目录中的另一个名为CMakeLists.txt的文件中

cmake_minimum_required(VERSION 2.8.2)

project(googletest-download NONE)

include(ExternalProject)
ExternalProject_Add(googletest
        GIT_REPOSITORY    https://github.com/google/googletest.git
        GIT_TAG           release-1.10.0
        SOURCE_DIR        "${CMAKE_CURRENT_BINARY_DIR}/googletest-src"
        BINARY_DIR        "${CMAKE_CURRENT_BINARY_DIR}/googletest-build"
        CONFIGURE_COMMAND ""
        BUILD_COMMAND     ""
        INSTALL_COMMAND   ""
        TEST_COMMAND      ""
        )

它做什么?

您添加到主CMakeList中的内容将以CMakeLists.txt.in文件中指定的版本下载GTest和GMock git项目。然后它将构建它们,并将构建路径包括在您的主项目中。

来源:GoogleTest Git