cmake-modulesapple-clang

Using C++ 20 modules with CMake using AppleClang 16 with macOS


I'm trying to test C++ 20 modules and I wasn't able to get it working. Then I saw this simple example project that assumably should work. I'm still getting same error.

CMake Error in CMakeLists.txt: The target named "foo" has C++ sources that may use modules, but the compiler does not provide a way to discover the import graph dependencies. See the cmake-cxxmodules(7) manual for details. Use the CMAKE_CXX_SCAN_FOR_MODULES variable to enable or disable scanning.

https://www.kitware.com/import-cmake-the-experiment-is-over

This question seemed slightly similar but it seemed to have g++ version that does not support modules. AFAIK, clang 16 should support it. Getting started with CMake >= 3.28 and C++20 modules

I have:

So I copied the CMakeLists.txt from the example:

cmake_minimum_required(VERSION 3.28)
project(std_module_example CXX)

# Turning off extensions avoids an issue with the clang 16 compiler
# clang 17 and greater can avoid this setting
set(CMAKE_CXX_EXTENSIONS OFF)
# Set the version of C++ for the project
set(CMAKE_CXX_STANDARD 20)
# Create a library
add_library(foo)
# Add the module file to the library
target_sources(foo
  PUBLIC
    FILE_SET CXX_MODULES FILES
      foo.cxx
)
# Create an executable
add_executable(hello main.cxx)
# Link to the library foo
target_link_libraries(hello foo)

Then tried running cmake:

% CXX=clang++ CC=clang cmake -G Ninja -S . -B build
-- The CXX compiler identification is AppleClang 16.0.0.16000026
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (0.2s)
CMake Error in CMakeLists.txt:
  The target named "foo" has C++ sources that may use modules, but the
  compiler does not provide a way to discover the import graph dependencies.
  See the cmake-cxxmodules(7) manual for details.  Use the
  CMAKE_CXX_SCAN_FOR_MODULES variable to enable or disable scanning.


-- Generating done (0.0s)
CMake Generate step failed.  Build files cannot be regenerated correctly.

I have tried setting that CMAKE_CXX_SCAN_FOR_MODULES to ON and OFF but it does not seem to have any effect.

I would assume that modules should work with macOS also... What am I doing wrong..?


Solution

  • I would assume that modules should work with macOS also... What am I doing wrong..?

    Modules work with the upstream LLVM version of Clang on MacOS, which you can install using e.g. Homebrew.

    Unfortunately Apple doesn't ship the clang-scan-deps tool either as part of Xcode or in the Command Line Tools package, meaning that CMake's module support doesn't work with Apple's version of Clang.