How to use c++20 modules with CMake?

后端 未结 4 542
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-03 22:27

Clang and MSVC already supports Modules TS from unfinished C++20 standard. Can I build my modules based project with CMake or other build system and how?

I tried bui

4条回答
  •  囚心锁ツ
    2021-01-03 23:06

    I was not able to find Cmake support for modules. Here is an example how to use modules using clang. I am using Mac and this example works ok on my system. It took me quite a while to figure this out so unsure how general this is across linux or Windows.

    Source code in file driver.cxx

    import hello;
    int main() { say_hello("Modules"); } 
    

    Source code in file hello.cxx

    #include 
    module hello;
    void say_hello(const char *n) {
      std::cout << "Hello, " << n << "!" << std::endl;
    }
    

    Source code in file hello.mxx

    export module hello;
    export void say_hello (const char* name);
    

    And to compile the code with above source files, here are command lines on terminal

    clang++ \
      -std=c++2a                        \
      -fmodules-ts                      \
      --precompile                      \
      -x c++-module                     \
      -Xclang -fmodules-embed-all-files \
      -Xclang -fmodules-codegen         \
      -Xclang -fmodules-debuginfo       \
      -o hello.pcm hello.mxx
    
    clang++ -std=c++2a -fmodules-ts -o hello.pcm.o -c hello.pcm
    
    clang++ -std=c++2a -fmodules-ts -x c++ -o hello.o \
      -fmodule-file=hello.pcm -c hello.cxx
    
    clang++ -std=c++2a -fmodules-ts -x c++ -o driver.o \
      -fmodule-file=hello=hello.pcm -c driver.cxx
    
    clang++ -o hello hello.pcm.o driver.o hello.o
    

    and to get clean start on next compile

    rm -f *.o
    rm -f hello
    rm -f hello.pcm
    

    expected output

    ./hello
    Hello, Modules!
    

    Hope this helps, all the best.

提交回复
热议问题