开发者

static variables in c

Static variables when declared in a file cannot be accessed from outside the file. But 开发者_运维技巧if we declare a static variable inside a file and a global pointer and then assign the address of the static variable to the pointer and then externing the pointer, it can be accessed.

So is it right saying that static variables can't be accessed directly but it can be accessed indirectly using global pointers and then externing?


It is not correct to say that static variables "cannot be accessed" from outside. Being declared static has absolutely nothing to do with the possibility of the outside access.

When some entity is declared static it only means that this entity will not be associated with other entities of the same name in other translation units.

For example, when you declare two extern variables names a in different translation units, these variables are actually the same, single variable. When you declare two static variables named a in different translation units, these variables are two different independent variables. This is what static does in C. Nothing else.

Speaking in more everyday terms, it is not possible to link to static variables from outside, i.e. it is not possible to ask linker to let us access static variable by name from outside. However, it is always possible to access it in some other way, like through a pointer, assuming that you managed to obtain that pointer somehow.


Think of variable names of static and external linkage as addresses like "maddy's house" and "123 foo street", respectively. The former is only meaningful to people who know you, while the latter is meaningful to others as well due to an established convention. But even if "maddy's house" doesn't have a street address, it still has a latitude and longitude you could give to somebody who wants to fire a missile at it. :-)


The static keyword in 'C' just restricts the scope of the variable to that specific translation unit(i.e that 'C' file.).In otherwords it restricts the linkage of that variable.and nothing else.and In C all static,global and auto variables can be accessed via pointers in their lifetime.there is not way to prevent that.


Anything within a process can be accessed if you have a pointer to it, barring architecture-specific mechanisms for restricting access.Redundantly saying that a variable can be accessed via a pointer is redundant.


The variable cannot be accessed and there will be no name clashing with this variable name and no one will be able to find the symbol of this variable.

But of course you can always access it via a pointer. The whole memory (stack + heap) of the process can be accessed via pointers and there is no way to prevent that.

Using static variable is not a security to prevent access to it from outside a module.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜