2

I have a Visual Studio CMake project. This is the CMakeListst.txt file:

cmake_minimum_required (VERSION 3.13)
project(googletest-cmake)

include(FetchContent)
FetchContent_Declare(googletest
    GIT_REPOSITORY https://github.com/google/googletest
    GIT_TAG release-1.11.0)
FetchContent_GetProperties(googletest)
if(NOT googletest_POPULATED)
  FetchContent_Populate(googletest)
  add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BUILD_DIR})
endif()

add_executable (CMakeProject4 "CMakeProject4.cpp" )
target_link_libraries(CMakeProject4 PRIVATE gtest_main)

The CMakeProject4.cpp file is trivial:

#include <gtest/gtest.h>

TEST(TestSuiteSample, TestSample)
{
    ASSERT_EQ(6, 1+5);
}

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

When I run "Build", this is the error I get: Error LNK2038 mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in test.obj testRunner C:\GTestWithCMakeFetchContent\VSBuild\gmock_maind.lib(gtest-all.obj) 1
error screenshot

Serban Stoenescu
  • 3,136
  • 3
  • 22
  • 41
  • The error message looks like ... it is about **other project**. It mentions `test.obj` file and `gmock_main` library, but you neither have a source named `test` nor you use `gmock` (gtest is not gmock). – Tsyvarev Nov 23 '21 at 22:58

1 Answers1

0

I just ran into this too and think I found the culprit.

Try adding this to your CMakeLists.txt:

set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)

The GoogleTest release notes include the following:

##### Visual Studio Dynamic vs Static Runtimes

By default, new Visual Studio projects link the C runtimes dynamically but
GoogleTest links them statically. This will generate an error that looks
something like the following: gtest.lib(gtest-all.obj) : error LNK2038: mismatch
detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value
'MDd_DynamicDebug' in main.obj

GoogleTest already has a CMake option for this: `gtest_force_shared_crt`

Enabling this option will make gtest link the runtimes dynamically too, and
match the project in which it is included.

See also:

jacobq
  • 11,209
  • 4
  • 40
  • 71