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?

4

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I do not believe you are correct because int var; is a variable declaration and definition. The fact that you can use it right away proves it is also a definition, does it not?
The C99 standard calls that a "tentative definition"; The "multiple definition" error message (and I) are still using the old K&R terminology.
Yeah, that is it, as I just found out from @Cool Guy's comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.