Search code examples
cmakevisual-studio-2017c++-climanaged-c++

How can I build a managed C++/CLI DLL library using CMake?


I need to build a C++/CLI DLL as part of a larger CMake build. I found no preferred way to do this when I checked the documentation.

I tried to set up the CMake file for building a regular shared library:

cmake_minimum_required(VERSION 3.20.0)

project(ExampleProject LANGUAGES CXX)

add_library(Example SHARED)
add_subdirectory(src)  # All source files are added here...

target_compile_features(Example PRIVATE cxx_std_17)
target_compile_definitions(Example PRIVATE
    UNICODE _UNICODE WIN32 DEBUG)
target_compile_options(Example PRIVATE
    /CLR /MP /W3 /Zi /Od /MDd /Zc:__cplusplus)
target_link_options(Example PRIVATE
    /DEBUG /LTCG /NXCOMPAT /DYNAMICBASE)

Yet, CMake adds the option /RTC1 incompatible with /CLR. So I wonder if there is managed C++ support for visual studio already built in CMake.

How do I build a managed C++/CLI DLL library using CMake?


Solution

  • CMake provides COMMON_LANGUAGE_RUNTIME target property for adjust "managed" aspects of C++ code.

    E.g. for make the target to contain a mixed (unmanaged/managed) code, set this property to the empty string:

    set_target_properties(Example PROPERTIES COMMON_LANGUAGE_RUNTIME "")
    

    Note, that property COMMON_LANGUAGE_RUNTIME is supported only for Visual Studio generators. E.g. for Ninja generator configured with cl compiler the property will have no effect.