Google Mock 和 Vcpkg 未解决的外部符号错误

Unresolved external symbol error with Google Mock and Vcpkg

我用一个模拟创建了一个简单的 C++ 测试项目 class:

#include <gtest/gtest.h>
#include <gmock/gmock.h>

class TestMock
{
public:
    MOCK_CONST_METHOD0(Method1, void());
};

TEST(Test, Test1)
{
    TestMock mock;
}

int main(int argc, char * argv[])
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

我使用 Visual Studio 2017 (15.3.3)。这是一个具有所有默认设置的 x86 调试项目。

我已将 gtest.lib 和 gmock.lib 添加到 linker。当我编译 link 时,出现此错误:

1>------ Build started: Project: ConsoleApplication1, Configuration: Debug Win32 ------
1>ConsoleApplication1.obj : error LNK2001: unresolved external symbol "class testing::internal::Mutex testing::internal::g_linked_ptr_mutex" (?g_linked_ptr_mutex@internal@testing@@3VMutex@12@A)
1>ConsoleApplication1.obj : error LNK2001: unresolved external symbol "class testing::internal::Mutex testing::internal::g_gmock_mutex" (?g_gmock_mutex@internal@testing@@3VMutex@12@A)
1>d:\Develop\CPP\ConsoleApplication1\Debug\ConsoleApplication1.exe : fatal error LNK1120: 2 unresolved externals
1>Done building project "ConsoleApplication1.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

我已经用Vcpkg下载了gtest包。它被编译为 32 位 DLL。 Gtest 工作正常,但是当我实例化模拟 class 时,出现 linking 错误。我也用 CMake 项目测试过,我得到了同样的错误。

摘自 Murat Şeker 的评论:

Add "GTEST_LINKED_AS_SHARED_LIBRARY" preprocessor definiton to your project. See : github.com/google/googletest/issues/292

这对我有用。