简体   繁体   English

外部函数原型和静态定义

[英]extern function prototype and static definition

I am working on getting FreeGLUT to build on OSX and am running into many instances of the same problem. 我正在努力使FreeGLUT可以在OSX上构建,并且正在遇到同一问题的许多实例。 Many of the functions exist only in the .c files. 许多功能仅存在于.c文件中。

Here's an example 这是一个例子

extern void fghRestoreState( void );

static void fghRestoreState( void ){...}

I have a limited understanding of C, but the compiler errors seem to make sense: 我对C的了解有限,但是编译器错误似乎很有意义:

src/Common/freeglut_gamemode.c:252: error: static declaration of ‘fghRestoreState’ follows non-static declaration
src/Common/freeglut_gamemode.c:43: error: previous declaration of ‘fghRestoreState’ was here

My question is, is there any reason they set it up this way? 我的问题是,他们有任何理由设置这种方式吗? Would it compile on other platforms correctly? 它可以在其他平台上正确编译吗?

The keyword extern in front of the function means external linkage . 该函数前面的关键字extern表示外部链接
It enables you to use functions defined in other Translation units to your own source file. 它使您可以将其他转换单元中定义的功能用于自己的源文件。
In Simple words, It enables you to use the fghRestoreState() in another file which does not include the declaration of it. 简而言之,它使您可以在不包含fghRestoreState()声明的另一个文件中使用它。

Whereas, the keyword static implies an Internal Linkage , that is the function should be visible only in the file in which is it defined and declared. 而关键字static表示Internal Linkage ,即该函数仅在定义和声明该文件的文件中可见。
In Simple words, it tells the compiler I will be using this function only in this source file so hide it from all the other files in my project. 用简单的话说,它告诉编译器我将仅在此源文件中使用此功能,因此将其对我项目中的所有其他文件隐藏。

The error since as stated above there is a conflict in using the two keywords together. 由于出现上述错误,因此将两个关键字一起使用会产生冲突。
You cannot tell the compiler to enable all files to see this function(using extern ) & again tell it, hide it from all other files(using static ). 您不能告诉编译器使所有文件都能看到此功能(使用extern )并再次告诉它,将其对所有其他文件隐藏(使用static )。

So choose the keyword as per your usage of the function. 因此,请根据您对函数的使用情况选择关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM