开发者

Incrementing a global static int in main

Here's my code:

File DataTypes.h

static int count=0;

File TreeOps.h

#include"DataTypes.h"
void printTree(Tree* ptr)

File TreeOps.c

#include"TreeOps.h"
void printTree(pointer){
count++;  // incrementing the count;
printf("%d",counter);
}

File TreeMain.c

#include"TreeOps.h"
printTree(pointer); // all the necessary declarations are done.
printf("%d",count);

If in printTree function the prin开发者_StackOverflowtf gives count=1; while in main function it gives me 0.

Why?


static variable in this context means: every c file has its own variable instance. Remove static definition in h-file:

extern int count;

and add this to one of c files:

int count = 0;

extern means: this is forward declaration. By defining a variable as extern, you tell to compiler that count has int type, and this variable is created somewhere. Actually, this variable is created in one and only one c file. You can use it in any c file where DataTypes.h is included. In the file where this variable is created, compiler uses it. In all other file this variable becomes external reference, which is resolved later by linker.


First off, defining data or functions in header files is a bad practice in C programming. In DataTypes.h you don't just declare the count variable, but you define it.

What actually happens is that the count is defined separately in each translation unit and you end up with two variables after linking. The linker doesn't merge them because they are marked static, that means they should be local to the translation unit.

If you want the count variable to be shared between the TreeOps.c and TreeMain.c translation units, you must use extern in the header file which only declares it:

extern int count;

And then define it globally as int count in either of TreeOps.c or TreeMain.c.


You don't have a "global static int" in your program. Entities declared as static cannot possibly be "global". The whole point of declaring something static is to make it local to a specific translation unit. This is exactly what you've done: you have declared two completely independent static variables in two different translation units. Each variable is local to its own translation unit. Then you are modifying one of these variables and printing the other. No wonder that the other remains unchanged.

In this case you have to decide what it is exactly you want. You can either have your variable as a global variable or as a static variable, but not both at the same time. "Global variable" and "static variable" are mutually exclusive concepts. So, what is it you want: global or static?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜