1

When I #include one header file in one module unit's global module fragment, I encountered some link error provided by MSVC and GCC together.

Firstly, I have one header file "Header.h" like this:

#pragma once
int f();

const int value = f();

And then, I defined a primary module interface unit [m1.ixx OR m1.cpp] like this:

module;
#include "Header.h"

export module m1;

export {
    inline int value2 = 0; // Not use anything in Header.h
}

Lastly, I import the module in "main.cpp" and build the example, the "main.cpp" like this:

import m1;
#include <iostream>

int main()
{
    using namespace std;
    cout << value2 << endl;
}

I got some link errors from GCC11:

/usr/bin/ld: /tmp/ccEkMykg.o: in function `__static_initialization_and_destruction_0(int, int)':

m1.cpp:(.text+0x1e): undefined reference to `f()'

and similarly link errors from MSVC:

Severity Code Description Project File Line Suppression State Error LNK1120 1 unresolved externals Study2 C:\Users\Glx\source\repos\Study2\x64\Debug\Study2.exe 1

Severity Code Description Project File Line Suppression State Error LNK2019 unresolved external symbol "int __cdecl f(void)" (?f@@YAHXZ) referenced in function "void __cdecl `dynamic initializer for 'value''(void)" (??__Evalue@@YAXXZ) Study2 C:\Users\Glx\source\repos\Study2\Study2\m1.ixx.obj 1

In my understanding, the declaration of the variable value and the function f() should be discarded because they are the declarations in the global module fragment and not be used by the module unit, so it's okay even if I don't provide the definition for the function f().

Did I understand it wrong?

1 Answer 1

2

“Discarded” in the context of modules just means that it’s not found by lookup from template definitions in the module (being instantiated as part of compiling a client). It doesn’t mean the same thing as a discarded statement in if constexpr. The definition of value plainly odr-uses f, so it must be defined somewhere.

Meanwhile, you shouldn’t have internal-linkage things like value in a header file at all.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.