Search code examples
c++cmakefmtc++-modules

How to use fmt with c++20 module and c++ 23 standard library module in cmake?


I have a minimal sample:

import fmt;
import std;
int main(int argc, char* argv[])
{
    auto v = std::vector<int>{1, 2, 3};
    fmt::print("{}", fmt::join(v, ", "));
    return 0;
}
cmake_minimum_required(VERSION 3.30 FATAL_ERROR)

set(CMAKE_CXX_STANDARD 23)
set(CMAKE_EXPERIMENTAL_CXX_IMPORT_STD "0e5b6991-d74f-4b3d-a41c-cf096e0b2508")
set(CMAKE_CXX_MODULE_STD 1)

project(main LANGUAGES CXX)

add_executable(main main.cpp)

include(FetchContent)
FetchContent_Declare(
        fmt
        GIT_REPOSITORY https://github.com/fmtlib/fmt
        GIT_TAG        0c9fce2ffefecfdce794e1859584e25877b7b592) # 11.0.2
FetchContent_MakeAvailable(fmt)
#target_link_libraries(main fmt::fmt)
target_sources(main
        PUBLIC FILE_SET CXX_MODULES
        FILES
        ${fmt_SOURCE_DIR}/src/fmt.cc
)
target_include_directories(main PRIVATE ${fmt_SOURCE_DIR}/include)

But it didn't work and it show join is not found(not overloaded) So I ask someone for help if there is a more helpful example for use fmt with c++20 module in cmake.

I have also notice this:

import fmt;

int main() {
  fmt::print("Hello, modules!\n");
}
cmake_minimum_required(VERSION 3.11)
project(HELLO CXX)

set(CMAKE_CXX_EXTENSIONS OFF)
add_subdirectory(fmt)
add_executable(hello hello.cc)
target_link_libraries(hello fmt)

it only work with clang and make. Ninja with gcc or msvc,even clang will get various errors...(wholly different for three)

I can't find other examples use fmt in c++20 or c++23 standard with google. Both C++ 20 or C++ 23 example is beneficial for me and other persons interested in it.


Solution

  • The method described in Simple usage of C++20 modules is what is currently supported in {fmt}.

    hello.cc:

    import fmt;
    
    int main() {
      fmt::print("Hello, modules!\n");
    }
    

    CMakeLists.txt:

    cmake_minimum_required(VERSION 3.11)
    project(HELLO CXX)
    
    set(CMAKE_CXX_EXTENSIONS OFF)
    add_subdirectory(fmt)
    add_executable(hello hello.cc)
    target_link_libraries(hello fmt)
    

    Building with clang:

    CXX=clang++ cmake -DFMT_MODULE=ON .
    make
    

    Unfortunately, only clang is known to fully work at the moment. GCC's implementation of modules is incomplete as of version 14.2, resulting in internal compiler errors. MSVC has various issues as well although there were reports that it was made to compile {fmt} with various workarounds.