Hi what could be the usage of static and extern pointer ?? if they exist
相关问题
- Multiple sockets for clients to connect to
- Do the Java Integer and Double objects have unnece
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
See How to correctly use the extern keyword in C
And Internal static variables in C, would you use them?
Essentially, "static" (in standard C) when used in a function allows a variable not to be wiped out as it normally would once the function ends (i.e., it retains its old value each time the function is called). "Extern" expands the scope of a variable so it can be used in other files (i.e., it makes it a global variable).
Suppose I have a pointer that I want to make globally available to multiple translation units. I want to define it in one place (foo.c), but allow multiple declarations for it in other translation units. The "extern" keyword tells the compiler that this is not the defining declaration for the object; the actual definition will appear elsewhere. It just makes the object name available to the linker. When the code is compiled and linked, all of the different translation units will be referencing the same object by that name.
Suppose that I also have a pointer that I do want to make globally available to functions within a single source file, but not have it visible to other translation units. I can use the "static" keyword to indicate that the name of the object not be exported to the linker.
Suppose that I also have a pointer that I want to use only within a single function, but have that pointer's value preserved between function calls. I can again use the "static" keyword to indicate that the object has static extent; memory for it will be allocated at program startup and not released until the program ends, so the object's value will be preserved between function calls.
short answer. Static is persistent so if you declare it in a function, when you call the function again the value is the same as it was last time. If you declare it globally, it is only global in that file.
Extern means it declared globally but in a different file. (it basically means this variable does exist and this is what its defined as).
Short answer: they don't exist. C99 6.7.1 says "At most, one storage-class specifier may be given in the declaration specifiers in a declaration".
extern
andstatic
are both storage class specifiers.To answer your question about when they could be used, a couple of simple examples:
A static pointer could be used to implement a function that always returns the same buffer to the program, allocating it the first time it is called:
An extern (i.e. global) pointer could be used to allow other compilation units to access the parameters of main: