This post will talk a little bit about the C/C++ keyword "static" and its use.
static as a key word can be used in three distinct occasions in C:
1. a static local variable declared within a function. The value of the static variable remains between function invocations.
2. a static variable declared within a module (a file for example), but outside any function bodies. Such a variable can only be accessed by functions within the module, but not functions in other modules. It's a localized global variable.
3. a static function declared in a module. Such a function has a scope of the module, with only functions in the module in which it's declared can call it.
For embedded Linux, a program's static variables (and global variables) are actually in the program's data segment, and exist until the program terminates. (Since compiler and linker know their existence and their types, they are pre-allocated.) To be more accurate, these with initial values are in the data segment, while these without initial values are in the program's BSS segments with "0" as initial values.
This is different for local variables declared in a function (auto variables), and params passed over to functions, they got their storage in the thread's stack(usually every thread of the program has a stack). And memory allocated by malloc() is from the program's heap(there's typically one heap for the program).
Now for static in C++. There are:
1. static data members of class. static data members are associated to a class instead of an object of the class. There is only one memory copy of a static data member for all the objects.
2. static methods. Again, a static method is associated to a class instead of an object. A static method is just like a regular function. The only difference is that it can access private and protected static data members of the class. And if you make a static method public, it can be called just like a function, with the class's name and a double "::" in front of it.
Subscribe to:
Post Comments (Atom)
i was in search of difference between static member and static function.Your article helped me to find the difference.thanx for yyour valuable information .
ReplyDeleteRegards
embedded systems