【问题标题】:How to set up a gtest project with cmake with a custom lib path如何使用带有自定义库路径的 cmake 设置 gtest 项目
【发布时间】:2022-01-01 08:20:58
【问题描述】:

我正在尝试使用 cmake 生成带有 gtest 的 Visual Studio 项目,并带有以下 cmake 文件..

cmake_minimum_required(VERSION 3.13)
set(CMAKE_CXX_STANDARD 11)

find_package(GTest REQUIRED)
message("GTest_INCLUDE_DIRS = ${GTest_INCLUDE_DIRS}")

add_library(commonLibrary LibraryCode.cpp)

add_executable(mainApp main.cpp)
target_link_libraries(mainApp commonLibrary)

add_executable(unitTestRunner testRunner.cpp)
target_link_libraries(unitTestRunner commonLibrary ${GTEST_LIBRARIES} pthread)

我在这个特定路径下载并编译了 gTest; C:\Users[MyUserName]\Documents\Libraries\gTest

但是,当我尝试在 cmake 文件上调用 cmake.. 时,我遇到了以下错误

  Could NOT find GTest (missing: GTEST_LIBRARY GTEST_INCLUDE_DIR
  GTEST_MAIN_LIBRARY)

我需要做什么才能让 cmake 找到这些路径?

【问题讨论】:

  • FWIW,gtest 是一个很好的选择,只使用FetchContent() 而不是与安装路径搏斗。它甚至是文档中使用的示例。
  • “我在 ... 下载并编译了 gTest” - 您在构建后是否安装 GTest?有关自定义安装的提示 CMake,您可以设置 GTEST_ROOT 变量(如 documentation 中所述)或 CMAKE_PREFIX_PATH 变量,如 that my answer 中所述。

标签: c++ cmake googletest


【解决方案1】:

为了能够使用 find_package,您必须先手动安装 googletest。 另一方面,FetchContent() 将从指定的源 url 获取 cmake 内容,并且对 FetchContent_MakeAvailable() 的调用将使其 cmake 工件在您的 CMakeLists 中可用。 txt.

示例用法如下:

cmake_minimum_required(VERSION 3.14)
include(FetchContent)
FetchContent_Declare(
        googletest
        GIT_REPOSITORY https://github.com/google/googletest.git
        GIT_TAG        703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
)
FetchContent_MakeAvailable(googletest)

# enable cmake testing
enable_testing()

# add test exe target, and link it with gtest_main library
add_executable(YourTestTarget hello.cc)
target_link_libraries(YourTestTarget gtest_main)

# this will include GoogleTest script and calls test discovery function defined in it, so you donot have to create main function for tests, they will be auto discovered
include(GoogleTest)
gtest_discover_tests(YourTestTarget)

它将从 googletest git 发布标签中获取内容并将其安装到 cmake-build 文件夹中的 deps 目录中。然后,它的工件将可用于您的 CMakeLists.txt。

请注意,要使用 FetchContent 和 FetchContent_MakeAvailable,您需要将 cmake 至少升级到 cmake14。

【讨论】:

  • FetchContent_MakeAvailable() 从 cmake 3.14 开始可用,这让这个过程更加简洁,这毫无价值。如果 OP 可以将他们的 cmake_minimum_required() 从 3.13 更改为至少该版本,那将非常值得。
  • 谢谢,这是真的,FetchContent_MakeAvailable 至少需要 cmake3.14。我编辑。
猜你喜欢
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
  • 2011-03-20
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多