-->

Linking C++ modules TS using clang

2020-03-31 06:23发布

问题:

I'm trying to use C++ modules TS with clang.

I've created two files:

// foo.cppm
export module foo;

export void test() {
}

and

// bar.cpp
import foo;

int main() {
  test();
  return 0;
}

I compile foo.cppm with this command

clang++ --std=c++17 -fmodules-ts --precompile foo.cppm -o foo.pcm

It compiles without an error and creates a foo.pcm file, but when i try to compile a binary with this command:

clang++ --std=c++17 -fmodules-ts -fprebuilt-module-path=. -fmodule-file=foo.pcm bar.cpp

it prints an error:

/tmp/bar-f69a1f.o: In function `main':
bar.cpp:(.text+0x10): undefined reference to `test()'

I tried it with clang 7 trunk and clang 6. Also i tried different std options and this command:

clang++ --std=c++17 -fmodules-ts -fmodule-file=foo.pcm bar.cpp -o bar

And nothing helps.

Interesting enough that if one module uses symbols from other, clang compiles these modules. So as i understand the problem is in linking stage.

What can be a problem?

回答1:

Like what https://blogs.msdn.microsoft.com/vcblog/2015/12/03/c-modules-in-vs-2015-update-1/ says, .cppm (.ixx) translates to .pcm (.ifc) and .o (.obj).

But unlike cl.exe, which automatically produce these two files, Clang's .o file must be compiled from its .pcm file:

clang++ --std=c++17 -fmodules-ts -c foo.pcm -o foo.o

With foo.cppm and bar.cpp above, the commands would be like:

clang++ --std=c++17 -fmodules-ts --precompile foo.cppm -o foo.pcm
clang++ --std=c++17 -fmodules-ts -c foo.pcm -o foo.o
clang++ --std=c++17 -fmodules-ts -fprebuilt-module-path=. foo.o bar.cpp


回答2:

In the producing module (foo.cppm) you need to omit the keyword export from the module definition.

// foo.cppm
module foo;

export void test() {
}

Everything else should work fine.