Reputation: 63
I need to use a global variable in multiple translation units, so I put
int g_exit_status;
in a header file and included that header in my source files. The default value for global variables is zero, but I need to use a specific value. I tried to specifying a value (e.g. 90), but then I received this error while compiling:
duplicate symbol '_g_exit_status' in:
/var/folders/zz/zyxvpxvq6csfxvn_n0000kch0004l4/T/main-422e60.o
/var/folders/zz/zyxvpxvq6csfxvn_n0000kch0004l4/T/parsing-328bc4.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [minishell] Error 1
Upvotes: 0
Views: 302
Reputation: 24726
The line
int g_exit_status;
is a tentative definition, which will act as a definition unless that variable is defined somewhere else in the same translation unit (i.e. in the same .c
file). In the latter case, it will instead act as a declaration.
The line
int g_exit_status = 90;
is a definition.
The line
extern int g_exit_status;
is a declaration.
A definition is also a declaration, but not vice-versa.
You must declare the variable g_exit_status
in all translation units in which it is used. However, according to the one-definition rule, you must define it in exactly one translation unit. You appear to be violating this rule by putting a definition inside a header file that is included by multiple translation units.
For the reasons stated above, the declaration
extern int g_exit_status;
should be inside the header file, but the definition
int g_exit_status = 90;
should only be inside a single .c
file, in order to not violate the one-definition rule.
Upvotes: 2