CMake 在 Windows 10 下使用 GTest - 致命错误 LNK1104:无法打开文件 'gtest.lib',但存在调试 'gtestd.lib'

CMake using GTest under Windows 10 - fatal error LNK1104: cannot open file 'gtest.lib', but debug 'gtestd.lib' is present

我已经为这个问题苦苦挣扎了一段时间: 我在 Windows 10 下使用 CMake 和 GTest,但我得到

(Link target) -> LINK : fatal error LNK1104: cannot open file 'gtest.lib' 

但是调试版本的库 'gtestd.lib' 存在于正确的文件夹中。 我使用的是简单的文件夹结构:

test [folder]
 - CMakeLists.txt
 - test.cpp

这意味着 GTest 以某种方式在调试目标下编译(即使使用 CMAKE_ARGS -DCMAKE_BUILD_TYPE=Release 我也无法强制执行),并且 CMake 生成无法识别此 GTest 调试目标的 VS 灵魂并尝试 link 针对不存在的 'gtest.lib' 版本。

我的测试 CMakeLists:

cmake_minimum_required(VERSION 2.8.12)

# Third-party library
include(ExternalProject)
ExternalProject_Add(googletest
    PREFIX "${CMAKE_BINARY_DIR}/lib"
    GIT_REPOSITORY "https://github.com/google/googletest.git"
    GIT_TAG "master"
    CMAKE_ARGS  -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/lib/installed
)

# Define ${CMAKE_INSTALL_...} variables
include(GNUInstallDirs)

# Specify where third-party libraries are located
link_directories(${CMAKE_BINARY_DIR}/lib/installed/${CMAKE_INSTALL_LIBDIR})
include_directories(${CMAKE_BINARY_DIR}/lib/installed/${CMAKE_INSTALL_INCLUDEDIR})

# This is required for googletest
find_package(Threads REQUIRED)

# target_sources 
# target_sources(cmake-sample2-main PUBLIC "../src/main.c")
set( SOURCES_TEST test.cpp )

# Test
add_executable(EmotionsModelLibraryTest ${SOURCES_TEST})
# Define the libraries this project depends upon
target_link_libraries(EmotionsModelLibraryTest libEmotionsModelLibrary gtest Threads::Threads)
# Make sure third-party is built before executable
add_dependencies(EmotionsModelLibraryTest googletest)

# has target scope—it adds x/y to the include path for target t.
# You want the former one if all of your targets use the include directories in question. You want the latter one if the path is specific to a target, or if you want finer control of the path's visibility. The latter comes from the fact that target_include_directories() supports the PRIVATE, PUBLIC, and INTERFACE qualifiers.
target_include_directories(EmotionsModelLibraryTest PRIVATE ${CMAKE_SOURCE_DIR}/include)

#possibly add to main after subdirectory
add_test(MyEmotionsModelLibraryTest EmotionsModelLibraryTest)

p.s。如果我手动将 Linker > Additional Dependencies 设置为 'gtestd.lib' 明确,它构建没有问题。此外,在 Ubuntu 18.04 下,使用 GTest 的 CMake 完美运行

你是如何构建你的项目的? 尝试使用:

cmake --build . --config Release

但是您可能会遇到 LNK2038 错误。

在此处了解该问题:LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MD_DynamicRelease' in file.obj

这里: Compile with /MT instead of /MD using CMake