Issue
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?
Solution
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).
Answered By - Lee Daniel Crocker Answer Checked By - Willingham (WPSolving Volunteer)