Robert Bean
Robert Bean

Reputation: 859

How compiler treat extern variable

This may be minor, but I'm curious about the reason.

This comes from a practice code of my friend:

#include <iostream>

using namespace std ;
extern int* PPPP;

void main(){
    cout<<"*PPPP"<<*PPPP<<endl;
}

By mistake, the PPPP is actually declared nowhere. But curiously we can compile this into a static lib. However, we can't make this into a dll, there are link errors (unresolved external sysmbol pppp)

We are guessing it's because that when making a static lib, the name PPPP (though extern) do has a space in memory anyhow, so, no problem occur in this.

We are not sure about this at all. We hope to hear some more and accurate information about this.

Thanks in advance.

Upvotes: 2

Views: 117

Answers (3)

tangrs
tangrs

Reputation: 9930

I'm guessing that when it's made into a static library, the linker assumes that any unresolved symbols will be available when fully linked.

If you link that static library to some program without a symbol called PPPP defined, it'll fail with a linker error.

Upvotes: 1

NPE
NPE

Reputation: 500257

When you say:

extern int* PPPP;

you are promising the compiler that PPPP is located in another translation unit.

The linker will try to find PPPP in the object files and libraries it's given and, if it can't, it'll issue an error.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409166

A static library is intended to be linked to another set of files, so it can contain undefined symbols as these would be resolved at a later stage (or not, in which case you get a linker error).

However a DLL, just like an executable, needs to be fully linked and so can't contain any undefined references.

Upvotes: 5

Related Questions