CMake-C++ Modules Minimal example

304 Views Asked by At

Since the cmake 3.28 release and following their first example I'm trying to create a minimal example with Module Partitions

This is my current minimal example and CMakeFile.txt

// Point2D.cxx
export module Math:Point2D;

export
struct Point2D
{
    int x_{};
    int y_{};
};
// Math.cxx
export module Math;
export import :Point2D;
// CMakeFile.txt
cmake_minimum_required(VERSION 3.28)
project(modules VERSION 0.1.0 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_SCAN_FOR_MODULES OFF)

add_library(Math-Point2D)
target_sources(Math-Point2D PUBLIC FILE_SET CXX_MODULES FILES
${CMAKE_CURRENT_SOURCE_DIR}/src/Math/Point2D.cxx
)

add_library(Math)
target_link_libraries(Math PRIVATE Math-Point2D)
target_sources(Math PUBLIC FILE_SET CXX_MODULES FILES
${CMAKE_CURRENT_SOURCE_DIR}/src/Math/Math.cxx
)

add_executable(modules main.cpp)
target_link_libraries(modules PRIVATE Math)

I've also tried to create just one library and inserting both files in the same lib, as follows:


add_library(Math)
target_sources(Math PUBLIC FILE_SET CXX_MODULES FILES
${CMAKE_CURRENT_SOURCE_DIR}/src/Math/Point2D.cxx
${CMAKE_CURRENT_SOURCE_DIR}/src/Math/Math.cxx
)

But none seems to work, I've tried with Makefile, and with make seems to (just compiling both files separately and linking all at the end...)

Any idea? I don't see any logic of creating Modules if I cannot create partitions...

1

There are 1 best solutions below

1
ComicSansMS On

You set CMAKE_CXX_SCAN_FOR_MODULES to OFF.

This disables dependency scanning for your main.cpp, so module dependencies from imports in that file will not be taken into account as build dependencies.

Don't set that option.

Also, you mention that you are using Makefiles. CMake's Module support does not work with the Makefiles generator, as is clearly stated in the documentation:

The list of generators which support scanning sources for C++ modules include:

  • Ninja

  • Ninja Multi-Config

  • Visual Studio 17 2022