Generate C# project using CMake

As of CMake 3.8.2, CSharp project generation is officially supported by CMake.

To build the default Visual Studio 2017 generated C#/WPF project using CMake, create a CMakeList.txt file as follows.

  • Project Declaration

      project(Example VERSION 0.1.0 LANGUAGES CSharp)
    
  • Include CMake CSharpUtilities if you are planning on using WPF or other designer properties.

      include(CSharpUtilities)
    
  • Add all cs, xaml, settings, properties

      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)
    
  • Link designer files, xaml files, and other properties files with their corresponding cs files

      csharp_set_designer_cs_properties(
          Properties/AssemblyInfo.cs
          Properties/Resources.Designer.cs
          Properties/Resources.resx
          Properties/Settings.Designer.cs
          Properties/Settings.settings)
    
      csharp_set_xaml_cs_properties(
          App.xaml
          App.xaml.cs
          MainWindow.xaml
          MainWindow.xaml.cs)
    
  • Set app App.xaml properties file as program entry point (if project is a WPF project)

      set_property(SOURCE App.xaml PROPERTY VS_XAML_TYPE "ApplicationDefinition")
    
  • Set other csproj file flags

      set_property(TARGET Example PROPERTY VS_DOTNET_TARGET_FRAMEWORK_VERSION "v4.6.1")
      set_property(TARGET Example PROPERTY WIN32_EXECUTABLE TRUE)
      // ...
    
  • Add libraries

      set_property(TARGET Example PROPERTY VS_DOTNET_REFERENCES
          "Microsoft.CSharp"
          "PresentationCore"
          "PresentationFramework"
          "System"
          "System.Core"
          "System.Data"
          "System.Data.DataSetExtensions"
          "System.Net.Http"
          "System.Xaml"
          "System.Xml"
          "System.Xml.Linq"
          "WindowsBase")
    

For a working WPF example, see https://github.com/bemehiser/cmake_csharp_example

For a WinForms example, see this answer.

Leave a Comment