Friday, 14 October 2016

[Important] static variable and static global variable


There might be a time, that you DID assigned some value to an static variable, but in a function somewhere else, the change cannot be detected. For example, I met this problem when using Software Timers (Particle) whose callback functions don't take any input parameters and return values. Therefore, global/static variables are the only way of communication to the callback functions.

Here is the reason:

(1) Global variables are stored in static region.(2*) Non-static global variable and static global variable are different where non-static global variable (just defined without keyword static) can be seen in all project source files while static global variable can only be seen in the source file where it is defined. 

So if I want some variables to be static and global, I should not put "static" in front of the definition otherwise functions in other source files cannot see it.

///////////////////////////////////////////////////////////////////////////////////////////////////////////

More, if coping with c++ objects...here are some tips.

(1) Dealing with Class/Object pointers:

First, variables declared as external must be defined. So you need to have
Logger *log;
in Logger.cpp. You can also initialize it there like this:
Logger *log = new Logger();
Second, you don't need any more declarations, that is you just need to include Logger.h, no need to declare another Logger variable in Foo.h, just use log from Logger.h.
(2) Dealing with objects

In .h file:
extern Timer _timerXXX;
extern Timer _timerYYY;
extern Timer _timerZZZ;

In .cpp file:
// give inputs to the constructors
Timer _timerXXX(x1, x2); 
Timer _timerYYY(y2, y2);
Timer _timerZZZ(z1, z2);

ref:
http://www.cnblogs.com/sideandside/archive/2007/03/29/692559.html
http://blog.csdn.net/ymangu666/article/details/22277673

ref more:
http://stackoverflow.com/questions/8362679/extern-pointer-initialization



No comments:

Post a Comment