我在 C++ / clr 项目中遇到过这种情况,我需要修改两个变量 -CMAKE_CXX_FLAGS
和CMAKE_CXX_FLAGS_DEBUG
. CMAKE_CXX_FLAGS
可以使用 修改set_source_files_properties / COMPILE_FLAGS
,但不能CMAKE_CXX_FLAGS_DEBUG
。我已经得出结论,在单独的文件夹中创建单独的、项目特定的 cmake 文件。如果项目是孤立的 - 那么变量修改将仅在当前 C++/clr 项目中起作用。
我想如果你想拥有多个 C++ 项目和多个 C++/clr 项目,至少将它们分开在两个不同的文件夹中(如果不是更多的话)是有意义的——特定于本机 C++,特定于托管 C++。
以类似的方式,您可以在 cmake 测试应用程序中找到:
https ://github.com/Kitware/CMake/blob/master/Tests/CSharpLinkToCxx/CMakeLists.txt
这是同样的事情,只是有更多的解释:
# These variables affects also other C++ projects, that's why separate cmake for this c++ dll
# Clr compiling requires these:
# "Enable C++ Exceptions" - "Yes (/EHsc)" => "Yes with SEH Exceptions (/EHa)"
string(REPLACE "/EHsc" "/EHa" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
# "Basic Run-time checks" - "Both (/RTC1, equiv. to /RTCsu) (/RTC1)" => "Default"
string(REPLACE "/RTC1" "" CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}")
这是一种方法。但是,如果您想在循环中生成本机 c++ 和托管 c++ 项目 - 一种方法是禁用全局标志:
# Disable global flag, configure on per project basis, using target_compile_options, target_link_options
string(REPLACE "/RTC1" "" CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}")
string(REPLACE "/INCREMENTAL" "" CMAKE_SHARED_LINKER_FLAGS_DEBUG "${CMAKE_SHARED_LINKER_FLAGS_DEBUG}")
#string(REPLACE "/EHsc" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
然后为每个项目单独配置每个项目设置,例如:
if(${is_managed})
# Managed C++ code
set_target_properties(${project} PROPERTIES VS_GLOBAL_CLRSupport "true")
set_property(TARGET ${project} PROPERTY VS_DOTNET_TARGET_FRAMEWORK_VERSION "v4.7.2")
# Being able to debug dll
target_link_options(${project} PRIVATE "$<$<CONFIG:Debug>:/ASSEMBLYDEBUG>")
# Disable incremental linking
target_link_options(${project} PRIVATE "$<$<CONFIG:Debug>:/INCREMENTAL:NO>")
# "Enable C++ Exceptions" - "Yes with SEH Exceptions (/EHa)"
set(compile_flags /EHa)
else()
# Native C++ code
# "Basic Run-time checks" - "Both (/RTC1, equiv. to /RTCsu) (/RTC1)" => "Default"
target_compile_options(${project} PRIVATE "$<$<CONFIG:Debug>:/RTC1>")
# Enable incremental linking
target_link_options(${project} PRIVATE "$<$<CONFIG:Debug>:/INCREMENTAL>")
# "Enable C++ Exceptions" - "Yes (/EHsc)"
set(compile_flags /EHsc)
endif()
set_target_properties(${project} PROPERTIES COMPILE_FLAGS ${compile_flags})