How do I use C++ modules in Clang?

前端 未结 2 573
你的背包
你的背包 2020-12-08 19:04

Modules are an alternative to #includes. Clang has a complete implementation for C++. How would I go about if I wanted to use modules using Clang now?


Using

2条回答
  •  星月不相逢
    2020-12-08 19:51

    As of this commit, Clang has experimental support for the Modules TS.

    Let's take the same example files (with a small change) as in the VS blog post about experimental module support.

    First, define the module interface file. By default, Clang recognizes files with cppm extension (and some others) as C++ module interface files.

    // file: foo.cppm
    export module M;
    
    export int f(int x)
    {
        return 2 + x;
    }
    export double g(double y, int z)
    {
        return y * z;
    } 
    

    Note that the module interface declaration needs to be export module M; and not just module M; like in the VS blog post.

    Then consume the module as follows:

    // file: bar.cpp
    import M;
    
    int main()
    {
        f(5);
        g(0.0, 1);
        return 0;
    }
    

    Now, precompile the module foo.cppm with

    clang++ -fmodules-ts --precompile foo.cppm -o M.pcm
    

    or, if the module interface extension is other than cppm (let's say ixx, as it is with VS), you can use:

    clang++ -fmodules-ts --precompile -x c++-module foo.ixx -o M.pcm
    

    Then build the program with

    clang++ -fmodules-ts -c M.pcm -o M.o
    clang++ -fmodules-ts -fprebuilt-module-path=. M.o bar.cpp
    

    or, if the pcm file name is not the same as the module name, you'd have to use:

    clang++ -fmodules-ts -fmodule-file=M.pcm bar.cpp
    

    I've tested these commands on Windows using the r303050 build (15th May 2017).

    Note: When using the -fprebuilt-module-path=. option, I get a warning:

    clang++.exe: warning: argument unused during compilation: '-fprebuilt-module-path=.' [-Wunused-command-line-argument]

    which appears to be incorrect because without that option, the module M is not found.

提交回复
热议问题