linker - How does referencing work when have two .c files with global variables of same symbols but different types? -


c

say have following c modules:

module 1

#include <stdio.h> int x; int main(){   foo();   printf("%i\n",x);   return 0; } 

module 2

double x; void foo(){   x = 3.14; } 

my question is: linker in case? in textbook i'm reading says compiler chooses 1 of 2 weak global variables linker symbol table. of these 2 chosen? or both chosen? if so, why? thanks.

c says undefined behavior.

(c99, 6.9p5) "if identifier declared external linkage used in expression (other part of operand of sizeof operator result integer constant), somewhere in entire program there shall 1 external definition identifier; otherwise, there shall no more one"

being undefined behavior means linker can abort linking process in presence of multiple external object definitions.

now linkers nice (or evil, can choose) , have default extensions handle multiple external object definitions , not fail in cases.

if using gcc , ld binutils, you'll error if 2 object explicitly initialized. example, have int x = 0; in first translation unit , double x = 0.0;.

otherwise, if 1 of external object not explicitly initialized (the situation in example) gcc silently combine 2 objects 1 symbol. can still ask linker report warning passing option --warn-common.

for example when linking modules:

gcc -wl,--warn-common module1.o module2.o

to linking process aborted, can request linker treat warnings errors using --fatal-warnings option (-wl,--fatal-warnings,--warn-common).

another way linking process aborted use -fno-common compiler option, explained @teppic in answer. -fno-common forbids external objects common symbol type @ compilation. if both module , link, you'll multiple definition linker error.

gcc -wall -fno-common -c module1.c module2.c

gcc module1.o module2.o


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -