Gcc links outward wrong?

I am relatively new to gcc and I am using 'gcc (tdm-1) 5.1.0'. By mistake, I encountered a very peculiar circumstance. I have reduced my concern to a very small reproducible example ...

main.cpp

extern int g;

int main(){
    return g;
}

      

someOtherFile.cpp

#include<windows.h>

RECT g;

      

this is compiling with

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

      

and it will be linked without error.

I am missing something, why is this allowed to bind?

+3


source to share


2 answers


3.5 / 10:

After all type adjustments (during which typedefs (7.1.3) are replaced by their definitions), the types specified by all declarations related to a given variable or function must be identical, except that declarations for an array object can specify array types. which differ in the presence or absence of a large array (8.3.4). Violation of this rule for type identity does not require diagnosis.



This last sentence means that the compiler and linker are not required to give you an error message. It is your job to figure this out.

+4


source


In C ++ it will not be referenced as the types g

do not match between main.cpp and someOtherFile.cpp. You should have int g

in someOtherFile.cpp or opposite extern RECT g;

in main.cpp.

In C this will compile and link, but in C ++. Compile compile and link as C ++:

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

      

Alternatively, you can use the following 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 (since there is no point in specifying RECT for int), but it will be similar to what you were trying to do.

The variable is g

internally someOtherFile.cpp

unrelated to another extern int g

one declared in main.cpp. Basically, it int g

just isn't defined anywhere, and for this reason the linker won't work.

Apparently this will actually compile and link with g ++, while the Microsoftsoft proxy will go wrong with this type of error.

0


source







All Articles