try_compile and genex in CMAKE_MSVC_RUNTIME_LIBRARY

On Windows 11, ninja 1.11.1 and cmake 3.30.3 with VS 2022.

When I configure the following CMakeLists.txt

cmake_minimum_required(VERSION 3.18...3.30 FATAL_ERROR)

set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")

project(cppTango LANGUAGES CXX)

try_compile(SOME_FLAG
            SOURCE_FROM_CONTENT main.cpp "int main(int, char**){}"
            OUTPUT_VARIABLE OUT)

message(STATUS "${OUT}")

with

cmake -G Ninja -B build -S . -DCMAKE_BUILD_TYPE=Release

I get

-- Change Dir: 'E:/projekte/cppTango/build/CMakeFiles/CMakeScratch/TryCompile-3luz9k'

Run Build Command(s): E:/projekte/common-orga-and-tools/tools/windows/ninja.exe -v cmTC_4ae17
[1/2] "C:\PROGRA~1\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.41.34120\bin\Hostx64\x64\cl.exe"  /nologo /TP   /DWIN32 /D_WINDOWS /EHsc  /Ob0 /Od /RTC1 -MTd -Zi /showIncludes /FoCMakeFiles\cmTC_4ae17.dir\main.cpp.obj /FdCMakeFiles\cmTC_4ae17.dir\ /FS -c E:\projekte\cppTango\build\CMakeFiles\CMakeScratch\TryCompile-3luz9k\main.cpp
[2/2] C:\Windows\system32\cmd.exe /C "cd . && "C:\Program Files\CMake\bin\cmake.exe" -E vs_link_exe --intdir=CMakeFiles\cmTC_4ae17.dir --rc="C:\PROGRA~2\Windows Kits\10\bin\10.0.26100.0\x64\rc.exe" --mt="C:\PROGRA~2\Windows Kits\10\bin\10.0.26100.0\x64\mt.exe" --manifests  -- "C:\PROGRA~1\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.41.34120\bin\Hostx64\x64\link.exe" /nologo CMakeFiles\cmTC_4ae17.dir\main.cpp.obj  /out:cmTC_4ae17.exe /implib:cmTC_4ae17.lib /pdb:cmTC_4ae17.pdb /version:0.0 /machine:x64  /debug /INCREMENTAL /subsystem:console  kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib && cd ."


-- Configuring done (0.4s)
-- Generating done (0.0s)
-- Build files have been written to: E:/projekte/cppTango/build

Note the -MTd where I would expect a -MT.

It does work if I use

set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded")

without generator expressions. Is that working as intended? I would expect that generator expressions in CMAKE_MSVC_RUNTIME_LIBRARY are working.

Does it help if you pass CMAKE_BUILD_TYPE down into the try-compile?

try_compile(SOME_FLAG
            SOURCE_FROM_CONTENT main.cpp "int main(int, char**){}"
            CMAKE_FLAGS -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}  #<=== added
            OUTPUT_VARIABLE OUT)

Thanks for the reply, yes that fixes the issue. I’ll see how large the fallout is on other platforms.

Reread the documentation again 1 and found CMAKE_TRY_COMPILE_CONFIGURATION which solves it as well. And seems to be the official way.

Yes, that seems preferrable indeed, as it will also work with multi-config generators. I learned something new, thanks.

You might want to move the Solution marker to your post about this, so that people are not misled by what turns out to be an insufficient workaround.

1 Like