cppwinrt Documentation

Official C++ developer resources and documentation for microsoft/cppwinrt with 1.9k stars. Verified technical context for AI.

1,878 stars C++ C++ 7 files ยท ~7,126 tokens
RAW Doc

Technical Documentation: microsoft/cppwinrt

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Overview (`README.md`)

The C++/WinRT language projection

C++/WinRT is an entirely standard C++ language projection for Windows Runtime (WinRT) APIs, implemented as a header-file-based library, and designed to provide you with first-class access to the modern Windows API. With C++/WinRT, you can author and consume Windows Runtime APIs using any standards-compliant C++17 compiler.

Building C++/WinRT

Don't build C++/WinRT yourself - just download the latest version here: https://aka.ms/cppwinrt/nuget

Working on the compiler

If you really want to build it yourself, the simplest way to do so is to run the build_test_all.cmd script in the root directory. Developers needing to work on the C++/WinRT compiler itself should go through the following steps to arrive at an efficient inner loop:

  • Open a dev command prompt pointing at the root of the repo.
  • Open the cppwinrt.sln solution.
  • Choose a configuration (x64, x86, Release, Debug) and build projects as needed.

If you are working on an ARM64 specific issue from an x64 or x86 host, you will need to instead:

  • Open the cppwinrt.sln solution
  • Build the x86 version of the "cppwinrt" project first
  • Switch to your preferred configuration and build the test binaries and run them in your test environment

Comparing Outputs

Comparing the output of the prior release and your current changes will help show the impact of any updates. Starting from
a dev command prompt at the root of the repo after following the above build instructions:

  • Run build_projection.cmd in the dev command prompt
  • Run build_prior_projection.cmd in the dev command prompt as well
  • Run prepare_versionless_diffs.cmd which removes version stamps on both current and prior projection
  • Use a directory-level differencing tool to compare _build\$(arch)\$(flavor)\winrt and _reference\$(arch)\$(flavor)\winrt

Testing

This repository uses the Catch2 testing framework.

  • From a Visual Studio command line, you should run build_tests_all.cmd to build and run the tests. To Debug the tests, you can debug the associated _build\$(arch)\$(flavor)\<test>.exe under the debugger of your choice.
  • Optionally, you can install the Catch2Adapter to run the tests from Visual Studio.

Overview (`nuget/readme.md`)

Microsoft.Windows.CppWinRT NuGet Package

Overview

Please visit Microsoft.Windows.CppWinRT for official Microsoft-signed builds of the NuGet package. See also the C++/WinRT VSIX, which provides C++/WinRT project templates and debug visualization.

To add build support for C++/WinRT vcxproj projects, add a reference to the Microsoft.Windows.CppWinRT NuGet package. This customizes your project's build rules to automatically generate C++/WinRT projection headers, enabling you to both consume and produce Windows Runtime classes.

C++/WinRT detects Windows metadata required by the project, from:

  • Platform winmd files in the SDK (both MSI and NuGet)
  • NuGet package references containing winmd files
  • Other project references producing winmd files
  • Raw winmd file references
  • Interface definition language (IDL) files in the project

For any winmd file discovered above, C++/WinRT creates reference (consuming) projection headers. Client code can simply #include these headers, which are created in the generated files directory (see below).

For any IDL file contained in the project, C++/WinRT creates component (producing) projection headers. In addition, C++/WinRT generates templates and skeleton implementations for each runtime class, under the generated files directory.

Details

C++/WinRT configures build rules for the following tools:

  • C++ compiler
  • C++/WinRT compiler
  • MdMerge utility
  • Midlrt utility
  • Xaml compiler

It sets the following project properties and item metadata:

Property Value Description
PreferredToolArchitecture x64 Enables the compiler to use more memory
CanReferenceWinRT true Enables native project references (e.g., to WinMD files)
GeneratedFilesDir *$(IntDir)Generated Files\ Sets the folder for C++/WinRT generated source files
XamlLanguage CppWinRT Directs the Xaml compiler to generate C++/WinRT code
ClCompile.CompileAsWinRT *false Enables ISO C++ compilation (disables C++/CX)
ClCompile.LanguageStandard *stdcpp17 Enables C++17 language features
ClCompile.AdditionalOptions /bigobj Enables support for large object files
ClCompile.AdditionalIncludeDirectories GeneratedFilesDir Adds $(GeneratedFilesDir) to the C++ include dirs
Link.AdditionalDependencies WindowsApp.lib Umbrella library for Windows Runtime imports
Midl.AdditionalOptions /reference ... Enables faster compilation with winmd references (versus idl imports)
Midl.EnableWindowsRuntime true Enables Windows Runtime semantics
Midl.MetadataFileName Unmerged%(Filename).winmd Generates unmerged metadata in a temporary location
Midl.GenerateClientFiles, GenerateServerFiles, GenerateStublessProxies, GenerateTypeLibrary, HeaderFileName, DllDataFileName, InterfaceIdentifierFileName, ProxyFileName, TypeLibraryName *nul, *None, *false Disable unnecessary output
*If not already set

Generated Files

The generated files directory created by C++/WinRT contains two subfolders:

  • sources: runtime class skeleton implementations
  • winrt: reference projection headers

Customizing

C++/WinRT behavior can be customized with these project properties:

Property Value Description
CppWinRTLibs *true | false Enables the Link item metadata settings above
CppWinRTModernIDL *true | false Enables the Midl item metadata settings above
CppWinRTVerbosity low | *normal | high Sets the importance of C++/WinRT build messages (see below)
CppWinRTNamespaceMergeDepth *1 Sets the depth of namespace merging (Xaml apps require 1)
CppWinRTRootNamespaceAutoMerge true | *false Sets the namespace merge depth to be the length of the root namespace
CppWinRTMergeNoValidate true | *false Disables mdmerge validation
CppWinRTUsePrefixes *true | false Uses a dotted prefix namespace convention (versus a nested folder convention)
CppWinRTPath ...\cppwinrt.exe NuGet package-relative path to cppwinrt.exe, for custom build rule invocation
CppWinRTParameters "" Custom cppwinrt.exe command-line parameters (be sure to append to existing)
CppWinRTFastAbi true | *false Enables Fast ABI feature for both consuming and producing projections
CppWinRTProjectLanguage C++/CX | *C++/WinRT Selects the C++ dialect for the project. C++/WinRT provides full projection support, C++/CX permits consuming projection headers.
CppWinRTOptimized true | *false Enables component projection optimization features
CppWinRTGenerateWindowsMetadata true | *false Indicates whether this project produces Windows Metadata
CppWinRTEnableDefaultPrivateFalse true | *false Indicates whether this project uses C++/WinRT optimized default for copying binaries to the output directory
CppWinRTBuildModule true | *false Generates per-namespace C++20 module interface units (.ixx) alongside projection headers
CppWinRTModuleInclude namespace list Semicolon-delimited namespaces to include in module generation (default: all)
CppWinRTModuleExclude namespace list Semicolon-delimited namespaces to exclude from module generation
*Default value

To customize common C++/WinRT project properties:

  • right-click the project node
  • expand the Common Properties item
  • select the C++/WinRT property page

InitializeComponent

In older versions of C++/WinRT, Xaml objects called InitializeComponent from constructors. This can lead to memory corruption if InitializeComponent throws an exception.

cpp
void MainPage::MainPage()
{
    // This pattern should no longer be used
    InitializeComponent();
}

C++/WinRT now calls InitializeComponent automatically and safely, after object construction. Explicit calls to InitializeComponent from constructors in existing code should now be removed. Multiple calls to InitializeComponent are idempotent.

If a Xaml object needs to access a Xaml property during initialization, it should override InitializeComponent:

cpp
void MainPage::InitializeComponent()
{
    // Call base InitializeComponent() to register with the Xaml runtime
    MainPageT::InitializeComponent();
    // Can now access Xaml properties
    MyButton().Content(box_value(L"Click"));
}

A non-Xaml object can also participate in two-phase construction by defining an InitializeComponent method.

cpp
void MyComponent::InitializeComponent()
{
    // Execute initialization logic that may throw 
}

[Windows|Microsoft]::UI::Xaml::Markup::ComponentConnectorT

A consequence of calling InitializeComponent outside construction is that Xaml runtime callbacks to IComponentConnector::Connect and IComponentConnector2::GetBindingConnector are now dispatched to the most derived implementations. Previously, these calls were dispatched directly to the class under construction, as the vtable had yet to be initialized. For objects with markup that derive from composable base classes with markup, this is a breaking change. Derived classes must now implement IComponentConnector::Connect and IComponentConnector2::GetBindingConnector by explicitly calling into the base class. The ComponentConnectorT template provides a correct implementation for these interfaces:

cpp
struct DerivedPage : winrt::Windows::UI::Xaml::Markup::ComponentConnectorT<DerivedPageT<DerivedPage>>

If overriding DerivedPage::InitializeComponent, ComponentConnectorT::InitializeComponent should be called instead of DerivedPageT::InitializeComponent:

cpp
void DerivedPage::InitializeComponent()
{
    // Call base InitializeComponent() to register with the Xaml runtime
    ComponentConnectorT::InitializeComponent();
    // Can now access Xaml properties from base or derived class
    MyBaseButton().Content(box_value(L"Click"));
}

C++20 Modules

C++/WinRT supports C++20 named modules as an alternative to #include-based consumption. Instead of #include <winrt/Windows.Foundation.h>, you can write import winrt.Windows.Foundation;.

See the C++/WinRT C++20 Modules Guide for the full guide (also shipped alongside this file as modules.md).

ProjectReference metadata Description
CppWinRTConsumeModule true | *false
*Default value

Troubleshooting

The msbuild verbosity level maps to msbuild message importance as follows:

Verbosity Importance
q[uiet] n/a
m[inimal] high
n[ormal] normal+
d[etailed], diag[nostic] low+
For example, if the verbosity is set to minimal, then only messages with high importance are generated. However, if the verbosity is set to diagnostic, then all messages are generated.

The default importance of C++/WinRT build messages is 'normal', but this can be overridden with the CppWinRTVerbosity property to enable throttling of C++/WinRT messages independent of the overall verbosity level.

Example:

msbuild project.vcxproj /verbosity:minimal /property:CppWinRTVerbosity=high ...

For more complex analysis of build errors, the MSBuild Binary and Structured Log Viewer is highly recommended.

Building, Testing

Be sure to get the latest nuget.exe from nuget.org and place it in your path.

Build the package by running build_nuget.cmd from a developer environment command line. For testing pass a version number that is much higher than your currently installed, like:

text
c:\repos\cppwinrt> .\build_nuget.cmd 5.0.0.0

Add the cppwinrt repo directory as a nuget source location and update your projects' references to point at it, update project references, then rebuild a test/sample project.


Overview (`vsix/readme.md`)

C++/WinRT Visual Studio Extension (VSIX)

Overview

Please visit C++/WinRT in the Visual Studio Marketplace for official Microsoft-signed builds of the C++/WinRT VSIX. See also the Microsoft.Windows.CppWinRT NuGet package, which provides build support for C++/WinRT vcxproj projects.

The C++/WinRT VSIX provides:

  • Debug visualization of C++/WinRT types, similar to the C# debugging experience.
  • Project and item templates to help you get started with consuming and authoring Windows runtime classes in modern C++.

Code Of Conduct (`docs/code_of_conduct.md`)

Microsoft Open Source Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct.

Resources:


Contributing (`docs/contributing.md`)

Contributing

Thanks for your interest in C++/WinRT! You are welcome to contribute by filing issues for problems you encounter.
Project maintainers will consider changes that improve compatibility or fix bugs.

The following process is required in order to have a pull request considered:

  • File an issue for any change you would like to propose. This can start a discussion so we can agree on an approach
    before you invest a large amount of time. Due to the large number of dependent projects, contributions that include
    compatibility risk or added complexity will generally be rejected.

  • Contributors will need the help of a project maintainer to verify the change with the Windows operating system
    build system. If a project maintainer is available to provide guidance and mentorship for the change, a pull request
    may be opened to begin the formal review process.

Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that
you have the right to, and actually do, grant us the rights to use your contribution. For details,
visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct.
For more information see the Code of Conduct FAQ or
contact [email protected] with any additional questions or comments.


Modules Design (`docs/modules-design.md`)

C++/WinRT Per-Namespace Modules: Design & Internals

This document describes the design and implementation of per-namespace C++20 module support in C++/WinRT. It is intended for cppwinrt maintainers and contributors.

Architecture Overview

The module system generates one C++20 named module per WinRT namespace. Each module encapsulates the same content as the traditional header files but exports declarations via WINRT_EXPORT in module purview.

text
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  winrt_numerics.ixx  โ”€โ”€  export module winrt_numerics;          โ”‚
โ”‚  winrt_base.ixx      โ”€โ”€  export module winrt_base;              โ”‚
โ”‚                          export import winrt_numerics;           โ”‚
โ”‚  winrt.Windows.Foundation.ixx                                   โ”‚
โ”‚                      โ”€โ”€  export module winrt.Windows.Foundation; โ”‚
โ”‚                          import std; export import winrt_base;   โ”‚
โ”‚                          import winrt.Windows.Foundation.Collections; โ”‚
โ”‚                          #include "winrt/impl/Windows.Foundation.0.h" โ”‚
โ”‚                          ...                                    โ”‚
โ”‚                          #include "winrt/Windows.Foundation.h"  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Key Design Decisions

Unconditional Guards

Module guards (WINRT_IMPL_BUILD_MODULE, WINRT_IMPORT_MODULE) are emitted unconditionally in generated projection headers โ€” they are always present regardless of whether -modules was passed to cppwinrt.exe. The -modules flag controls .ixx generation and whether generated component files (module.g.cpp, stub .cpp) use module imports. This means:

  • Projection headers generated without -modules still work correctly when later compiled inside a module interface unit
  • No regeneration of projection headers needed when switching between header and module consumption

WINRT_EXPORT Macro

WINRT_EXPORT is defined in base_macros.h (generated as winrt/base_macros.h):

  • When WINRT_IMPL_BUILD_MODULE is defined (inside .ixx compilation): export extern "C++"
  • Otherwise (header mode): empty

All namespace winrt::impl and namespace std blocks use WINRT_EXPORT so they export correctly from modules. The extern "C++" wrapping enables include-before-import compatibility (same technique as MSVC STL).

Per-Namespace vs Monolithic

Unlike the v1 approach (single import winrt;), v2 generates one module per namespace. This provides:

  • Finer granularity: Import only what you need
  • Better parallelism: Independent modules compile in parallel
  • Component module support: Component namespaces get their own modules

The trade-off is handling dependency cycles between namespaces (see SCC below).

This is enforced via the MSBuild CppWinRTConsumeModule metadata on ProjectReference โ€” it only points at the platform module builder, not at component projects.

Code Generator Pipeline

Entry Point: `main.cpp`

  1. Namespace enumeration: First pass determines which namespaces are module-eligible using module_filter (from -module_include/-module_exclude)

  2. Header generation: Standard header generation with optional dependency collection. When -modules is active and a namespace is in the module, write_namespace_*_h() functions populate ns_deps sets via the deps_ptr parameter

  3. Dependency graph construction: After all headers are generated, ns_deps_map contains the full namespace dependency graph

  4. SCC detection: Tarjan's algorithm (find_sccs()) identifies strongly-connected components

  5. Module generation: For each SCC:

    • Size 1: write_namespace_ixx() โ€” standalone module
    • Size > 1: write_namespace_scc_owner_ixx() for the owner (alphabetically first) + write_namespace_reexport_ixx() for others

CLI Options

Flag Description
-modules Enable .ixx generation
-module_include <ns>... Only generate modules for these namespace prefixes
-module_exclude <ns>... Skip these namespace prefixes

The module_filter is populated from these flags and checked against ALL cache namespaces (not just the projection filter). This is important for component builds where the platform namespaces are not being projected but their modules exist from a prior builder invocation.

Generated Files

File When Generated Purpose
winrt/base_macros.h Always with -base Macros for module builds (WINRT_EXPORT, etc.)
winrt/winrt_base.ixx -modules -base Core types module
winrt/winrt_numerics.ixx -modules -base Numerics module
winrt/winrt.<ns>.ixx -modules Per-namespace module

SCC (Strongly Connected Components)

The Problem

WinRT namespaces have cyclic dependencies. For example:

  • Windows.Foundation depends on Windows.Foundation.Collections (via IVector, IMap, etc.)
  • Windows.Foundation.Collections depends on Windows.Foundation (via IAsyncOperation, Uri, etc.)

C++20 modules cannot have circular imports. If module A imports module B, then module B cannot import module A.

The Solution: SCC Consolidation

Tarjan's algorithm identifies groups of namespaces that form dependency cycles. These groups (SCCs) are consolidated:

  1. Owner selection: The alphabetically first namespace in the SCC becomes the "owner"
  2. Owner module: Contains ALL declarations from ALL SCC namespaces. Forward-declares all types first, then includes headers in phase order (all *.0.h, then *.1.h, then *.2.h, then public headers)
  3. Re-export stubs: Other SCC members get thin .ixx files that just re-export the owner module

This means import winrt.Windows.Foundation; and import winrt.Windows.Foundation.Collections; both work โ€” they resolve to the same underlying module.

Example Generated Files

Owner (winrt.Windows.Foundation.ixx):

cpp
module;
#define WINRT_IMPL_BUILD_MODULE
#include "winrt/base_macros.h"
// ...

// This module is an SCC owner (cycle breaker). The following namespaces
// form a dependency cycle and are consolidated into this single module:
//   - Windows.Foundation
//   - Windows.Foundation.Collections
// Other SCC namespaces are emitted as re-export stubs.

export module winrt.Windows.Foundation;

import std;
export import winrt_base;

// Forward declarations for all SCC namespaces...
// #include all impl headers in phase order...

Re-export stub (winrt.Windows.Foundation.Collections.ixx):

cpp
// NOTE: This module does not define declarations of its own.
// It re-exports all declarations from the 'winrt.Windows.Foundation' module.
export module winrt.Windows.Foundation.Collections;
export import winrt.Windows.Foundation;

MSBuild Integration

Targets Flow

text
CppWinRTResolveModuleReferences  (resolves IFC paths from ProjectReference metadata)
    โ†“
CppWinRTMakePlatformProjection   (generates headers + .ixx for platform types)
CppWinRTMakeReferenceProjection  (generates headers + .ixx for referenced WinMDs)
CppWinRTMakeComponentProjection  (generates headers + .ixx for component types)
    โ†“
CppWinRTAddModuleInterfaces      (discovers .ixx files, adds to ClCompile items)
    โ†“
FixupCLCompileOptions            (MSVC module dependency scanner processes .ixx)
    โ†“
ClCompile                        (compiles .ixx โ†’ .ifc + .obj)

Key Properties

  • CppWinRTBuildModule: Enables -modules for all three projections (platform, reference, component), causing .ixx generation and compilation.
  • CppWinRTConsumeModule (ProjectReference metadata): Per-reference opt-in for IFC consumption. When set, suppresses -modules on the platform projection so the consumer uses pre-built IFCs from the referenced project instead of generating its own.
  • _CppWinRTConsumesPlatformModules: Internal property set by CppWinRTResolveModuleReferences when any ProjectReference has CppWinRTConsumeModule=true. Controls whether the platform projection receives -modules.

Cross-Project IFC Resolution

MSVC's module dependency scanner uses /ifcSearchDir for within-project module resolution. For cross-project modules, the scanner generates explicit /reference "module.name=path.ifc" entries based on the dependency scan results. The /ifcSearchDir pointing to the builder's $(IntDir) allows the scanner to find the pre-built IFCs.

Dependency Collection

During header generation, when -modules is active, each write_namespace_*_h() function receives a deps_ptr parameter. The writer's w.depends map is inspected to find referenced namespaces. Only namespaces that:

  1. Exist in the cache
  2. Have projected types
  3. Are in the module namespace set (or set is empty)

are added to the dependency set. Self-references are excluded. The union of dependencies from all four header files (*.0.h, *.1.h, *.2.h, <ns>.h) gives the complete dependency set for a namespace module.

Testing

test/test_cpp20_module/ (in-repo)

Standalone test built by the main solution. Uses a PreBuildEvent to run cppwinrt.exe with -modules -base -module_include "Windows.Foundation". Tests URI, events, collections, and coroutines.

test/nuget/ (NuGet integration)

Multi-project solution:

  • TestModuleBuilder: Static library that pre-builds platform modules
  • TestModuleComponent1: Component DLL (Greeter class), consumes builder's modules
  • TestModuleComponent2: Component DLL (GreeterGroup), depends on Component1
  • TestModuleConsumerApp: Console app, consumes builder + both components
  • TestModuleApp: Single-project that builds and consumes its own modules

Security (`docs/security.md`)

Security

Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include Microsoft, Azure, DotNet, AspNet, Xamarin, and our GitHub organizations.

If you believe you have found a security vulnerability in any Microsoft-owned repository that meets Microsoft's definition of a security vulnerability, please report it to us as described below.

Reporting Security Issues

Please do not report security vulnerabilities through public GitHub issues.

Instead, please report them to the Microsoft Security Response Center (MSRC) at https://msrc.microsoft.com/create-report.

If you prefer to submit without logging in, send email to [email protected]. If possible, encrypt your message with our PGP key; please download it from the Microsoft Security Response Center PGP Key page.

You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at microsoft.com/msrc.

Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:

  • Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
  • Full paths of source file(s) related to the manifestation of the issue
  • The location of the affected source code (tag/branch/commit or direct URL)
  • Any special configuration required to reproduce the issue
  • Step-by-step instructions to reproduce the issue
  • Proof-of-concept or exploit code (if possible)
  • Impact of the issue, including how an attacker might exploit the issue

This information will help us triage your report more quickly.

If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our Microsoft Bug Bounty Program page for more details about our active programs.

Preferred Languages

We prefer all communications to be in English.

Policy

Microsoft follows the principle of Coordinated Vulnerability Disclosure.


--- METRICS ---