initializing a static variable in header

Viewed 59832

I am new in programming in C, so I am trying many different things to try and familiarize myself with the language.

I wrote the following:

File q7a.h:

static int err_code = 3;
void printErrCode(void);

File q7a.c:

#include <stdio.h>
#include "q7a.h"

void printErrCode(void)
{
        printf ("%d\n", err_code);
}

File q7main.c:

#include "q7a.h"

int main(void)
{
        err_code = 5;
        printErrCode();

        return 0;
}

I then ran the following in the makefile (I am using a Linux OS)

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.

Why is this happening?

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 isn't the value 5 inserted into the static var (after all it is static and global)?

Thanks for the help.

4 Answers

When you declared a variable as a static it has only scope within a file ie.., it can be accessed only within a file. When you declare a static variable in a header file and include this header file in two .c file, then you are creating two different memory for two different ".c" files

When you print err_code directly in the Main function you would see its value as 5 instead 3, but you are calling a function printErrCode which is defined in a different file "q7a.c" for which err_code has a different memory location in which err_code memory is still 3 and it not updated and that is why you are getting the value as 3 instead of 5.

Since two memory is created and err_code is considered as two different variables having different memory with different file scope you will not see any linking errors.

Related