How Linkers Resolve Multiply Defined Global Symbols in C

775 views c
6

My Textbook says that:

"Functions and initialized global variables get strong symbols. Uninitialized global variables get weak symbols.Given a strong symbol and multiple weak symbols, choose the strong symbol"

So I create two files to see:

file1.c:

int number;

int main(int argc, char *argv[]) 
{
    printf("%d",number);
    return 0;
}

file2.c (just one line):

int number = 2018;

and I ran gcc -Wall -o program file1.c file2.c and the output is 0, which I can understand before I study linker ('number' in file1.c has been initialized to 0), but after I study how linker works, I start to wonder why the output is not 2018, since the 'number' in file2 is strong symbol(initialized global variable) and the 'number' in file1 is weak symbol, so the linker will choose the strong one whose value is 2018, so why the linker choose the weak symbol?

answered question

1 Answer

0

The number in file2.c is global, but still locally scoped just to that file. If you want file1.c to use number from file2.c you need to mark it as extern like this:

extern int number;

int main(int argc, char *argv[]) 
{
    printf("%d",number);
    return 0;
}

posted this

Have an answer?

JD

Please login first before posting an answer.