3

I stumbled upon this weird behaviour when compiling C programs using gcc.

Let's say we have these two simple source files:

fun.c

#include <stdio.h>

// int var = 10;   Results in Gcc compiler error if global variable is initialized
int var;

void fun(void) {
    printf("Fun: %d\n", var);
}

main.c

#include <stdio.h>
int var = 10;
int main(void) {
    fun();
    printf("Main: %d\n", var);
}

Surprisingly, when compiled as gcc main.c fun.c -o main.out this doesn't produce multiple definition linker error.

One would expect multiple definition linker error to occur just the same, regardless of global variable initialization. Does it mean that compiler makes uninitialized global variables extern by default?

Community
  • 1
  • 1
Marin Veršić
  • 404
  • 4
  • 10
  • 2
    Possible duplicate of [Two variables with same name and type, in two different .c files, compile with gcc](http://stackoverflow.com/questions/7189982/two-variables-with-same-name-and-type-in-two-different-c-files-compile-with-g) – LPs Mar 16 '16 at 16:09
  • http://stackoverflow.com/q/21275992/3049655 , http://stackoverflow.com/questions/1490693/tentative-definitions-in-c99-and-linking – Spikatrix Mar 16 '16 at 16:22
  • [This SO article](http://stackoverflow.com/questions/3095861/about-tentative-definition) might be helpful. – Jabberwocky Mar 16 '16 at 16:34
  • Related note, when accessing within a shared library, you can find both with dlsym(). This is what the RTLD_NEXT argument is for. I’m not aware of how the order is determined, however.Probably a good practice to avoid it, or share it by defining it once and using the extern keyword in other files. – adam Dec 25 '18 at 22:39

1 Answers1

1

A global variable can have any number of declarations, but only one definition. An initializer makes it a definition, so it will complain about having two of those (even if they agree).

Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55