Home > Enterprise >  Best practice to link modules split into multiple files with gcc/g
Best practice to link modules split into multiple files with gcc/g

Time:05-01

I would like to have a file containing only the declarations in a module and one or more files containing the definitions.

According to How to split a module into multiple files (and this awseome cppcon talk: https://youtu.be/nP8QcvPpGeM at 12:04) I should split my files like this:

Log.cpp:

export module Log;

int i = 0;
export void Log();

Log_imp.cpp:

module Log;

void Log() {
    std::cerr << "This is a log and i=" << i << "\n";
}

I can build both with g -11 -std=c 20 -fmodules-ts -c Log.cpp and g -11 -std=c 20 -fmodules-ts -c Log_imp.cpp respectively.

My main simply imports the Log module and calls the Log() function. Note that I have to link with both Log.o and Log_imp.o, otherwise I get linking errors.

Is it possible to have a single object file for a single module, without building a static library? If not, then should I link modules into a static library, or keep multiple .o files?

CodePudding user response:

Modules are basically orthogonal to the linking process. Each module file is its own translation unit and therefore will produce its own object file. You can combine them into a library (or a single object file), but otherwise, you're going to have to link to all such object file.

  • Related