← Back to Pull requests

C++20 module support v2 #1575

Closed
unknown closed this pull request without merging on May 20, 2026 20:17 UTC
View on GitHub
unknown unknown commented on Apr 25, 2026 03:37 UTC
Author

C++20 Module Support v2: Per-Namespace Modules (import winrt.Windows.Foundation;)

Overview

This PR adds per-namespace C++20 module support to C++/WinRT, building on the approach pioneered by @YexuanXiao's cppwinrtplus fork. Instead of a single monolithic import winrt; module (v1), each WinRT namespace gets its own named module:

import winrt.Windows.Foundation;
import winrt.Windows.Storage;

This provides finer-grained imports, better build parallelism, and first-class support for component authoring with modules.

---

Key Design Decisions

1. Unconditional guards, flag-controlled generation


Module awareness (guards, WINRT_EXPORT) is always present in projection headers. The -modules flag controls .ixx generation and whether generated component files (module.g.cpp, stub .cpp) use import vs #include. Projection headers themselves are identical regardless of -modules.

2. All three projections generate modules uniformly


When CppWinRTBuildModule=true, -modules is passed to the platform, reference, and component projections. There is no special module-specific handling that distinguishes these projections — the existing differences (e.g., -opt for components, -comp for component stubs) are pre-existing behavior.

3. Per-ProjectReference IFC consumption


CppWinRTConsumeModule is metadata on a ProjectReference, not a project-level property. When set, it suppresses -modules on the platform projection (since IFCs are already available from the referenced project) but does not affect the reference or component projections. This gives precise control over which pre-built IFCs to reuse.

4. SCC consolidation for cyclic namespaces


Tarjan's algorithm groups cyclic namespaces. The alphabetically-first namespace owns the module; others re-export it. Users can import winrt.AnyNamespace; regardless of SCC membership.

---

What's in This PR

Code generator (cppwinrt/)

| File | Changes |
|-|-|
| main.cpp | Added -modules, -module_include, -module_exclude CLI options. Two-pass namespace loop: first populates module namespace set, then generates headers with dependency collection. Tarjan's SCC algorithm. .ixx generation loop. |
| file_writers.h | write_macros_h(), write_module_preamble(), write_base_ixx(), write_numerics_ixx(), write_namespace_ixx(), write_namespace_scc_owner_ixx(), write_namespace_reexport_ixx(). Unconditional WINRT_IMPORT_MODULE / WINRT_IMPL_BUILD_MODULE guards on all generated headers. Component .g.h dual-path (import vs include). base.h now #includes winrt/base_macros.h instead of inlining macros. |
| code_writers.h | wrap_module_aware_includes_guard() updated comment. wrap_impl_namespace() uses WINRT_EXPORT namespace winrt::impl. |
| settings.h | Added bool modules, std::set module_include/exclude, winmd::reader::filter module_filter. |

String literals (strings/)

| Change | Files |
|-|-|
| namespace winrt::impl → WINRT_EXPORT namespace winrt::impl | All files with impl namespace |
| namespace std → WINRT_IMPL_STD_EXPORT namespace std | 4 files (hash/coroutine_traits specializations) |
| base_macros.h refactored as canonical shared macros | Generated as winrt/base_macros.h, used by both base.h and .ixx global fragments |
| New base_source_location.h | Source location macros + slim_source_location (split from base_macros.h) |
| New base_module_ixx_preamble.h | Global module fragment for .ixx files |
| New base_module_base_ixx.h | winrt_base.ixx template |
| New base_module_numerics_ixx.h | winrt_numerics.ixx template |
| base_extern.h | Added WINRT_EXPORT to handler function pointers for module/non-module linkage |
| base_fast_forward.h | Added WINRT_EXPORT fallback definition |

MSBuild integration (nuget/)

User-facing properties:

| Property / Metadata | Scope | Default | Description |
|-|-|-|-|
| CppWinRTBuildModule | Project property | false | Enables -modules for all three projections, generating .ixx files alongside headers |
| CppWinRTModuleInclude | Project property | (all) | Semicolon-delimited namespace prefixes to include in module generation |
| CppWinRTModuleExclude | Project property | (none) | Semicolon-delimited namespace prefixes to exclude from module generation |
| CppWinRTConsumeModule | ProjectReference metadata | false | Suppresses platform .ixx generation and uses pre-built IFCs from the referenced project |

Internal targets (not directly configured by users):

| Target | Purpose |
|-|-|
| CppWinRTAddModuleInterfaces | Discovers generated .ixx files and adds them as ClCompile items with module compilation metadata |
| CppWinRTGetModuleOutputs | Exports GeneratedFilesDir / IntDir / OutDir for cross-project IFC resolution |
| CppWinRTResolveModuleReferences | Calls CppWinRTGetModuleOutputs on ProjectReferences tagged with CppWinRTConsumeModule |

Test projects

| Project | Description |
|-|-|
| test/test_cpp20_module/ | Standalone test in main solution (9 test cases: URI, events, collections, coroutines, source_location) |
| test/nuget/TestModuleBuilder/ | Static library — pre-builds platform modules |
| test/nuget/TestModuleComponent1/ | Component DLL — Greeter class with Uri return |
| test/nuget/TestModuleComponent2/ | Component DLL — GreeterGroup, depends on Component1 |
| test/nuget/TestModuleConsumerApp/ | Console app — consumes builder + both components end-to-end |
| test/nuget/TestModuleApp/ | Single-project — builds and consumes its own modules |

Documentation

| File | Description |
|-|-|
| nuget/modules.md | User-facing adoption guide (Quick Start, properties, troubleshooting) |
| docs/modules-design.md | Maintainer design document (architecture, SCC, MSBuild flow) |
| .github/instructions/cppwinrt.instructions.md | AI agent instructions for the codebase |
| .github/instructions/modules.instructions.md | AI agent instructions for module-specific work |

---

Before / After: User Code

Header mode (unchanged)


#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Storage.h>

int main() {
    winrt::init_apartment();
    winrt::Windows::Foundation::Uri uri(L"https://example.com");
    auto folder = winrt::Windows::Storage::KnownFolders::DocumentsLibrary();
}

Module mode (new)


import winrt.Windows.Foundation;
import winrt.Windows.Storage;

int main() {
    winrt::init_apartment();
    winrt::Windows::Foundation::Uri uri(L"https://example.com");
    auto folder = winrt::Windows::Storage::KnownFolders::DocumentsLibrary();
}

Component authoring with modules


// MyComponent.cpp (inside a component DLL)
#include "pch.h"

import winrt.Windows.Foundation;
import winrt.MyComponent;

#include "Greeter.h"
#include "Greeter.g.cpp"

namespace winrt::MyComponent::implementation {
    hstring Greeter::Greet() { return L"Hello from a module!"; }
}

---

Before / After: Generated Code

Namespace header (winrt/Windows.Foundation.h) — guard changes

Before (no module awareness):

#pragma once
#ifndef WINRT_Windows_Foundation_H
#define WINRT_Windows_Foundation_H
#include "winrt/impl/Windows.Foundation.Collections.2.h"
#include "winrt/impl/Windows.Foundation.2.h"
namespace winrt::impl { /* consume definitions */ }
namespace winrt::Windows::Foundation { /* class wrappers */ }
#endif

After (unconditional module guards):

#pragma once
#ifndef WINRT_Windows_Foundation_H
#define WINRT_Windows_Foundation_H
#ifndef WINRT_IMPORT_MODULE     // ← skips body when consumer imports the module
#ifndef WINRT_IMPL_BUILD_MODULE // ← skips includes when building inside a .ixx
#include "winrt/impl/Windows.Foundation.Collections.2.h"
#include "winrt/impl/Windows.Foundation.2.h"
#endif
WINRT_EXPORT namespace winrt::impl { /* consume definitions */ }
WINRT_EXPORT namespace winrt::Windows::Foundation { /* class wrappers */ }
#endif // WINRT_IMPORT_MODULE
#endif

New: Generated module interface (winrt.Windows.Foundation.ixx)

// WARNING: Please don't edit this file. It was generated by C++/WinRT
module;
#define WINRT_IMPL_BUILD_MODULE
#include <intrin.h>
#include <cstddef>
#include <version>
#include "winrt/base_macros.h"

export module winrt.Windows.Foundation;

// Module dependencies:
//   - std
//   - winrt_base (re-exported)
//   - winrt.Windows.Foundation.Collections

import std;
export import winrt_base;
import winrt.Windows.Foundation.Collections;

#include "winrt/impl/Windows.Foundation.0.h"
#include "winrt/impl/Windows.Foundation.1.h"
#include "winrt/impl/Windows.Foundation.2.h"
#include "winrt/Windows.Foundation.h"

New: SCC owner module (cycle breaker)

When namespaces form dependency cycles (e.g., Windows.Foundation ↔ Windows.Foundation.Collections), the alphabetically-first namespace becomes the SCC owner:

// winrt.Windows.Foundation.ixx (SCC owner)
export module winrt.Windows.Foundation;

// 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.

import std;
export import winrt_base;
// Forward declarations for all SCC types...
// All impl headers in phase order...

// winrt.Windows.Foundation.Collections.ixx (re-export stub)
// 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;

New: Component .g.h (dual-path)

#pragma once
// ...
#ifdef WINRT_IMPORT_MODULE
#include "winrt/base_macros.h"
import winrt.Windows.Foundation;
import winrt.MyComponent;
#else
#include "winrt/Windows.Foundation.h"
#include "winrt/MyComponent.h"
#endif
// ... component implementation scaffolding

---

Differences from the cppwinrtplus Fork

This implementation shares the same core architecture as @YexuanXiao's cppwinrtplus fork — per-namespace modules, Tarjan SCC cycle breaking, WINRT_EXPORT macro — but diverges in several areas:

Module naming


| | cppwinrtplus | This PR |
|-|-|-|
| Base module | winrt.base | winrt_base |
| Numerics module | winrt.numerics | winrt_numerics |
| Namespace modules | <Namespace>.ixx (e.g. Windows.Foundation.ixx) | winrt.<Namespace>.ixx (e.g. winrt.Windows.Foundation.ixx) |

The winrt. prefix on namespace modules avoids potential collisions if other code generators produce modules with the same namespace names. The winrt_base / winrt_numerics underscore form avoids a dotted name that could imply a namespace hierarchy.

Module namespace filtering


cppwinrtplus uses a CppWinRT.config XML file in the solution directory with <exclude><prefix> elements to exclude namespaces from module generation. This PR uses -module_include / -module_exclude CLI flags with prefix matching, exposed as CppWinRTModuleInclude / CppWinRTModuleExclude MSBuild properties. The CLI approach integrates directly into MSBuild response files without needing a separate config file, and supports both include and exclude semantics.

Guard macros


| | cppwinrtplus | This PR |
|-|-|-|
| Build-side guard | WINRT_MODULE | WINRT_IMPL_BUILD_MODULE |
| Consume-side guard | WINRT_CONSUME_MODULE | WINRT_IMPORT_MODULE |
| Guard conditionality | Conditional on -modules flag | Unconditional — always emitted |

Making guards unconditional means the -modules flag controls .ixx generation and module-aware component code generation (.g.cpp, module.g.cpp, stub .cpp), but does NOT change the content of projection headers — they work in both module and header mode without regeneration.

Builder/consumer architecture


cppwinrtplus does not have a concept of sharing pre-built IFCs across projects — each project builds all its own modules. This PR introduces:
  • CppWinRTBuildModule — project-level property to enable module generation for all three projections

  • CppWinRTConsumeModule — per-ProjectReference metadata that suppresses platform .ixx generation and lets the project use pre-built IFCs from the referenced project instead

  • CppWinRTGetModuleOutputs / CppWinRTResolveModuleReferences — Internal MSBuild targets for cross-project IFC path resolution
  • ---

    Acknowledgements

    Credit to @YexuanXiao and the cppwinrtplus fork for the per-namespace module architecture, SCC algorithm, and initial demonstration of viability. Also @sylveon, @Scottj1s, and @zadjii-msft for early module exploration and feedback on v1.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: YexuanXiao Review duration: 36999m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #1575"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 56.8% · Lower = rushed or shallow review
    56.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.5% · Safe to merge
    22.5%