1

Suppose i have 2 C src files, A1.C, A2.C, these are the contents:

A1.C

int x;
int main(){
     void f(void);

     x = 5; 
     f();
     printf("%d", x);

     return 0;
}

A2.C

int x;
void f() {  x = 4; }

the linker doesn't give me any errors despite the missing "extern" safe-word. i have 2 identical symbols. can someone explain why?

Medals
  • 131
  • 1
  • 4
  • 1
    Did you try to add some warning options like `-W` (for GCC) and so on ... ? – Unda Jun 28 '14 at 22:52
  • I believe that if you don't have extern the compiler will remove one of the redundant variables – apache Jun 28 '14 at 22:55
  • @apache It's unlikely. If it happens as you say, then the `extern` keywork would be useless. But maybe, the compiler consider the two variables as `static`. It would be easier to know if the question included the output produced by such a code. – Unda Jun 28 '14 at 22:58
  • @Unda: They are declared to have external linkage. Not giving a storage-class specifier means “external linkage” and `extern` means “linkage as already given, if none was given, external”. – mafso Jun 28 '14 at 23:34

1 Answers1

2

For gcc, you can use the -fno-common flag to turn this into an error.

The gcc documentation explains what's happening

-fno-common

In C code, controls the placement of uninitialized global variables. Unix C compilers have traditionally permitted multiple definitions of such variables in different compilation units by placing the variables in a common block. This is the behavior specified by -fcommon, and is the default for GCC on most targets.

On the other hand, this behavior is not required by ISO C, and on some targets may carry a speed or code size penalty on variable references.

The -fno-common option specifies that the compiler should place uninitialized global variables in the data section of the object file, rather than generating them as common blocks. This has the effect that if the same variable is declared (without extern) in two different compilations, you get a multiple-definition error when you link them.

See also Tentative definitions in C99 and linking

Community
  • 1
  • 1
nos
  • 223,662
  • 58
  • 417
  • 506