Dave
Dave

Reputation: 126

gcc linking externs incorrectly?

I'm relatively new to gcc and I'm using 'gcc (tdm-1) 5.1.0'. I've come across a very peculiar circumstance by mistake. I've shrunk my concern down to a very small reproducible example...

main.cpp

extern int g;

int main(){
    return g;
}

someOtherFile.cpp

#include<windows.h>

RECT g;

this I compile with

gcc -c someOtherFile.cpp
gcc main.cpp someOtherFile.o

and this will link without error.

Am I missing something here as to why this is allowed to link?

Upvotes: 3

Views: 110

Answers (2)

Pavel P
Pavel P

Reputation: 16843

In C++ it won't link as the types of g are non-matching between main.cpp and someOtherFile.cpp. You have to have int g in someOtherFile.cpp or opposite, extern RECT g; in main.cpp.

In C this will compile and link, but on in c++. Com compile and link as c++:

g++ -c someOtherFile.cpp
g++ -c main.cpp
g++ main.o someOtherFile.o -o test

Alternatively, you may use functions for this:

main.cpp

int g();

int main{
    return g();
}

someOtherFile.cpp

#include<windows.h>

RECT r;
int g()
{
    return (int)r;
}

Obviously not recommended (as there isn't much point to cast RECT to int), but that would be similar in effect to what you were trying to do.

Variable g inside someOtherFile.cpp isn't related to the other extern int g declared in main.cpp. In effect, the int g simply isn't defined anywhere and linker will fail at the end for this reason.

Apparently, this will actually compile and link by g++, while microsoft linker will error on this type of mistake.

Upvotes: 0

aschepler
aschepler

Reputation: 72271

3.5/10:

After all adjustments of types (during which typedefs (7.1.3) are replaced by their definitions), the types specified by all declarations referring to a given variable or function shall be identical, except that declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4). A violation of this rule on type identity does not require a diagnostic.

That last sentence means the compiler and linker are not required to give you an error message. It's your job to get it straight.

Upvotes: 4

Related Questions