C++20 modules API example

The recent Kitware CMake blog post on C++20 modules gives a standalone example for MSVC, GCC and Clang.

Note that CMake >= 3.25.3 (i.e. Nightly) is necessary for this to work. And to make it simple use MSVC if on Windows.

standalone CMakeLists.txt:

cmake_minimum_required(VERSION 3.25.3)
project(std_module_example CXX)
# https://www.kitware.com/import-cmake-c20-modules/

set(CMAKE_EXPERIMENTAL_CXX_MODULE_DYNDEP 1)
set(CMAKE_EXPERIMENTAL_CXX_MODULE_CMAKE_API "2182bf5c-ef0d-489a-91da-49dbc3090d2a")

if(NOT MSVC)
  message(FATAL_ERROR "only for MSVC for now.")
endif()

set(CMAKE_CXX_STANDARD 20)

file(WRITE foo.h
"class foo {
foo();
~foo();
void helloworld();
};"
)

file(WRITE foo.cxx
[=[
#include "foo.h"
#include <iostream>
foo::foo() = default;
foo::~foo() = default;
void foo::helloworld() { std::cout << "hello world\n"; }
]=]
)

file(WRITE main.cxx
[=[
#include "foo.h"

int main()
{
  foo f;
  f.helloworld();
  return 0;
}
]=]
)

add_library(foo)
target_sources(foo
  PUBLIC
    FILE_SET cxx_modules TYPE CXX_MODULES FILES
    foo.cxx
)
add_executable(hello main.cxx)