GoogleTest compile with MT_StaticRelease errors
Asked Answered
P

1

6

How can I force google test compile with /MT option? I saw that google test tries to compile with MT(internal_utils.cmake line 33):

  if (NOT BUILD_SHARED_LIBS AND NOT gtest_force_shared_crt)
    string(REPLACE "/MD" "-MT" ${flag_var} "${${flag_var}}")
  endif()

But it doesn't work (BUILD_SHARED_LIBS and gtest_force_shared_crt are disabled).
I gets error when my project compiles with MT:

gtest.lib(gtest-all.obj) : error LNK2038: mismatch detected for "RuntimeLibrary": value "MD_DynamicRelease" does not match value "MT_StaticRelease"

And more some LNK2005 and LNK4217. If I try to compile my project without MT, all compiles ok. How can I solve it? Thanks in advance!

Pride answered 16/9, 2020 at 17:35 Comment(2)
Welcome to Stack Overflow! The proper way to set the MSVC runtime in CMake (versions 3.15 and greater) is by using MSVC_RUNTIME_LIBRARY, as seen in the response here.Jerad
@squareskittles, do I need to do this for the "gtest" target?Pride
P
6

That if is a test, implementing a switch allowing you to configure it before including googletest.

It's also mentioned in the manual:

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.

So just set it in your project e.g. like this:

set(gtest_force_shared_crt on)

include(FetchContent)
FetchContent_Declare(googletest
        GIT_REPOSITORY https://github.com/google/googletest.git
        GIT_TAG main)
FetchContent_MakeAvailable(googletest)

enable_testing()
Palpable answered 17/12, 2021 at 19:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.