How to do `import std` with CMake

724 views Asked by At

According to this and CMake 3.28, we should be able to import std without any extra effort. But I'm getting the error Module 'std' not found with following simple demo.

import std;

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}
cmake_minimum_required(VERSION 3.28)
project(module_tst)

set(CMAKE_CXX_STANDARD 23)

add_executable(demo)
target_sources(demo
    PRIVATE
    main.cpp
)

import std works well in Visual Studio, as long as I checked C/C++ -> General -> Scan Sources for Module Dependencies. I found something similar in cmake document that is CXX_SCAN_FOR_MODULES but set it on makes no difference. Is there anything missing?

I'm using latest cmake 3.28 rc1 and VS 17.8.0 Preview 4.0

1

There are 1 answers

2
Jakkapong Rattananen On

After I did tried c++ module for few month. As far as I knew (for MSVC only).

  • import std was changed to import std.core here.
  • We must install c++ module for MSVC component. It wasn't selected by default. You could install them by goto Visual Studio Installer > Modify.
  • Module partition doesn't work with Ninja generator.
  • Must add /experimental:module when complie command even document say "enabled automatically by either /std:c++20 or /std:c++latest" link.
  • I still don't know how to make intellisense working with import std.core yet.

here my boilerplate.

cmake_minimum_required (VERSION 3.26)

set(CMAKE_EXPERIMENTAL_CXX_MODULE_CMAKE_API "2182bf5c-ef0d-489a-91da-49dbc3090d2a") #this require to enable c++ module feature in my cmake version
set(CMAKE_EXPERIMENTAL_CXX_MODULE_DYNDEP 1) # enable scan dependencies /scanDependencies
set(CMAKE_CXX_STANDARD 20) # it work with c++20 but has some warnning

project ("cmake_project")

add_compile_options(
   /EHsc 
   /experimental:module # require
   $<$<CONFIG:Release>:/O2>
)

add_library(my_lib)
target_sources(my_lib PUBLIC FILE_SET my_lib_fs TYPE CXX_MODULES FILES 
    "src/modules/ratt.ixx"
)# compile as c++ module

add_executable (main "src/main.cpp" )
target_link_libraries(main PRIVATE my_lib)