(1) keyword
extern
: it can be used both on variables and function declaration. And its purpose for both usages are the same, which is, to make one variable or function defined globally in one file visible by other source files. When used on a function declaration, it has the same effect as without it; all function declarations implicitly have the extern keyword stuck in front of them. The point is: it is much clearer to define the global in one place and then declare extern references to it in all other places. So it is a good programming practice and engineering. When you write reasonable big software in C you are going to need it for good software engineering and make linker happy. Do not put extern declarations in header files; put them in C source files!(2) keyword
static
: most confusing keyword to novice programmer. Again, it has two usage, one is on variables and other is on functions. When a variable is declared static, its lifetime is throughout the whole run of the program, and its scope is file scope if it is declared global otherwise local scope. When a function is declared static, that makes the function local to the file, in other words, file scope! (its visibility is only to the entire file it is declared, but not to other files.) Guess what?! That said, you can use static keyword to make things (either functions or global variables) 'private' to the local compilation unit! When you need public function, just don't make it static!Additional note, the difference between global static variables and global variables? The storage class for both kinds of variables are the same, meaning they are both put into the same region on memory and persist through the lifetime of the program. However, global variables are accessible from any other compilation units by using
extern
keyword whereas global static variables cannot! So global static variables have file scope while global variables have program scope!check this out: http://tinyurl.com/2a9zs3x
No comments:
Post a Comment