Search code examples
c++extern

Using extern to refer to a function defined in a different compilation unit


Due to some static data, I have a function

void foo(MyNamespace::bar)

defined in a certain compilation unit. But its point of use is in another compilation unit. So I use

namespace MyNamespace
{
    extern void foo(bar);
}

But the linker can't find the function definition. Am I misusing extern?


Solution

  • extern can be used for this kind of thing.

    Your problem is that the linker is expecting a function MyNamespace::foo(bar); due to the fact that your extern statement is within MyNamespace.

    You have two choices:

    1. use extern void foo(MyNamespace::bar); at your "point of use". Don't enclose that line within MyNamespace.

    2. Alternatively, enclose the function definition within MyNamespace.