首页 > 解决方案 > 使用 CMake 在同一解决方案中创建 C# 和 C++/CLR 项目(针对 Visual Studio 的 CMake)

问题描述

我想使用具有两个项目的 CMake 在 MSVC 中创建一个解决方案(在 CMake 词汇表中,一个 C# 执行程序和一个 C++/CLR 库)。

我怎样才能做到这一点?我发现的所有示例都是关于 CMake 中的一种类型的项目(所有 C++ 或 C#)。

澄清:

如果我想使用 CMake 创建一个 C++/CLR 项目,我可以编写如下代码:

cmake_minimum_required (VERSION 3.5)

project (TestCppClr)

if (NOT MSVC)
    message(FATAL_ERROR "This CMake files only wirks with MSVC.")
endif(NOT MSVC)


ADD_EXECUTABLE(testCppClr "${CMAKE_SOURCE_DIR}/main.cpp")
set_target_properties(testCppClr PROPERTIES COMMON_LANGUAGE_RUNTIME "")

如果我想创建一个针对 C# 的项目,我可以编写如下内容:

cmake_minimum_required (VERSION 3.5)

project(Example VERSION 0.1.0 LANGUAGES CSharp)

if (NOT MSVC)
    message(FATAL_ERROR "This CMake files only wirks with MSVC.")
endif(NOT MSVC)


add_executable(Example
App.config
App.xaml
App.xaml.cs
MainWindow.xaml
MainWindow.xaml.cs

Properties/AssemblyInfo.cs
Properties/Resources.Designer.cs
Properties/Resources.resx
Properties/Settings.Designer.cs
Properties/Settings.settings)

我找不到任何方法来组合这两个 CMake 文件,所以我可以在 C++/CLR 中创建一个可执行文件,在 C# 中创建另一个项目。

有什么办法可以做到这一点吗?

标签: c#visual-studiocmakec++-cli

解决方案


您当然可以在同一个 CMake 项目中同时拥有C++/CLI和 C# - 只需在调用project().

cmake_minimum_required (VERSION 3.5)

# Enable both C++ and C# languages.
project (TestCSharpAndCppClr VERSION 0.1.0 LANGUAGES CXX CSharp)

if(NOT MSVC)
    message(FATAL_ERROR "This CMake files only works with MSVC.")
endif(NOT MSVC)

# Create your C++/CLI executable, and modify its properties.
add_executable(testCppClr "${CMAKE_SOURCE_DIR}/main.cpp")
set_target_properties(testCppClr PROPERTIES COMMON_LANGUAGE_RUNTIME "")

# Create your C# executable.
add_executable(Example
App.config
App.xaml
App.xaml.cs
MainWindow.xaml
MainWindow.xaml.cs

Properties/AssemblyInfo.cs
Properties/Resources.Designer.cs
Properties/Resources.resx
Properties/Settings.Designer.cs
Properties/Settings.settings)

请注意,您应该使用 CMake 3.8 或更高版本来获得对 C# 的完整CMake 支持。此外,您的 C# 示例似乎缺少 CSharp 目标的一些基本 CMake 命令,如本响应所示。您应该能够根据需要将这些命令添加到同一CMakeLists.txt文件中,以修改 C# 源文件和 C# 目标的属性。


推荐阅读