P45 Imminent
P45 Imminent

Reputation: 8591

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?

Upvotes: 2

Views: 388

Answers (1)

Bathsheba
Bathsheba

Reputation: 234715

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.

Upvotes: 8

Related Questions