Search code examples
cextern

Why would link order matter with extern variables?


Once upon a time, my teacher at school showed some example of code with question "What will be the output?". It was something like this:

file1.c (just one line):

int a = 8;

file2.c:

#include <stdio.h>

int main(void) {
    int b = 20;
    extern int a;
    printf("%d", a + b);
}

Then, he compiled this two times: the first was something like this:

gcc file1.c file2.c -o prog_name

and the output was I guess 28; but then, he compiled in this way (or similar to this):

gcc file2.c file1.c -o prog_name

and the result was just different, I think it was 20.

Now, when I want to reproduce this "tricky question" I'm only getting 28 as the result, using these two different(?) methods to compile. I want to simply ask if this is order of source files when compiling matters and how to reproduce this example to working that as I remember it was. Is this even possible?


Solution

  • You are getting the correct, expected behaviour. Link order should not affect the output of the program — within broad limits. (If a pair of libraries implement a common function in different ways, then if you link with both libraries, the link order of the libraries would matter, but that's way more complex than what you're dealing with.)

    I recommend forgetting about the alternative behaviour since the originator is no longer available to be consulted.