views:

78

answers:

2

hey everyone.

i am new in programming in c, so i am trying all these things just to get the hang of the code.

so i worte the following:

// file: q7a.h
static int err_code = 3;
void printErrCode ();
///////////// END OF FILE /////////////////
// file: q7a.c
#include <stdio.h>
#include "q7a.h"
void printErrCode ()
{
printf ("%d ", err_code);
}
///////////// END OF FILE /////////////////
// file: q7main.c
#include "q7a.h"
int main()
{
err_code = 5;
printErrCode ();
return 0;
}
///////////// END OF FILE /////////////////

so i ran the following in the makefile (i am using a Linux system)

gcc –Wall –c q7a.c –o q7a.o
gcc –Wall –c q7main.c –o q7main.o
gcc q7main.o q7a.o –o q7

the output is 3.

my question is why?

if you initialize a static variable (in fact any variable) in the header file, so if 2 files include the same header file (in this case q7.c and q7main.c) the linker is meant to give an error for defining twice the same var?

and why isnt the value 5 inserted into the static var (after all it is static and global)?

thanx

+3  A: 

static means that the variable is only used within your compilation unit and will not be exposed to the linker, so if you have a static int in a header file and include it from two separate .c files, you will have two discrete copies of that int, which is most likely not at all what you want.

Instead, you might consider extern int, and choose one .c file that actually defines it (i.e. just int err_code=3).

EboMike
Don't you mean *define* instead of *declare* in your last sentence?
schot
Yep. Corrected.
EboMike
A: 

The static variables donot have external linkage which means they cannot be accessed outside the translation unit in which they are being defined. So in your case when q7.h is #include'ed in both translations units q7a.c and q7main.c ... two different copies exists in their corresponding .o files. That is why linker does not report error becuase both copies are not seen by linker while doing external symbol linkage.

Amit