小智 12
要回答关于何时可以使用它们的问题,请举几个简单的例子:
静态指针可用于实现一个总是向程序返回相同缓冲区的函数,在第一次调用它时分配它:
char * GetBuffer() {
static char * buff = 0;
if ( buff == 0 ) {
buff = malloc( BUFSIZE );
}
return buff;
}
Run Code Online (Sandbox Code Playgroud)
可以使用extern(即全局)指针允许其他编译单元访问main的参数:
extern int ArgC = 0;
extern char ** ArgV = 0;
int main( int argc, char ** argv ) {
ArgC = argc;
ArgV = argv;
...
}
Run Code Online (Sandbox Code Playgroud)
假设我有一个指针,我想让多个翻译单元全局可用。我想在一个地方(foo.c)定义它,但允许在其他翻译单元中对其进行多个声明。“extern”关键字告诉编译器这不是对象的定义声明;实际的定义将出现在其他地方。它只是使对象名称可供链接器使用。编译和链接代码时,所有不同的翻译单元都将通过该名称引用同一对象。
假设我还有一个指针,我确实希望使其对单个源文件中的函数全局可用,但不让它对其他翻译单元可见。我可以使用“static”关键字来指示对象的名称不导出到链接器。
假设我还有一个指针,我只想在单个函数中使用该指针,但在函数调用之间保留该指针的值。我可以再次使用“static”关键字来指示该对象具有静态范围;它的内存将在程序启动时分配,直到程序结束才释放,因此该对象的值将在函数调用之间保留。
/**
* foo.h
*/
#ifndef FOO_H
#define FOO_H
/**
* Non-defining declaration of aGlobalPointer; makes the name available
* to other translation units, but does not allocate the pointer object
* itself.
*/
extern int *aGlobalPointer;
/**
* A function that uses all three pointers (extern on a function
* declaration serves roughly the same purpose as on a variable declaration)
*/
extern void demoPointers(void);
...
#endif
/**
* foo.c
*/
#include "foo.h"
/**
* Defining declaration for aGlobalPointer. Since the declaration
* appears at file scope (outside of any function) it will have static
* extent (memory for it will be allocated at program start and released
* at program end), and the name will be exported to the linker.
*/
int *aGlobalPointer;
/**
* Defining declaration for aLocalPointer. Like aGlobalPointer, it has
* static extent, but the presence of the "static" keyword prevents
* the name from being exported to the linker.
*/
static int *aLocalPointer;
void demoPointers(void)
{
/**
* The static keyword indicates that aReallyLocalPointer has static extent,
* so the memory for it will not be released when the function exits,
* even though it is not accessible outside of this function definition
* (at least not by name)
*/
static int *aReallyLocalPointer;
}
Run Code Online (Sandbox Code Playgroud)