Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

c - initializing a static variable in header

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
", 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...