Marin Veršić
Marin Veršić

Reputation: 403

GCC:Multiple definitions of a global variable doesn't give linker error

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?

Upvotes: 3

Views: 4044

Answers (1)

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13196

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).

Upvotes: 1

Related Questions