C语言 函数声明为静态但从未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15681442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:51:14  来源:igfitidea点击:

function declared static but never defined

cgcc-warning

提问by pankanaj

I have a header file suppose abc.h, where i have function declaration as:

我有一个头文件假设 abc.h,其中我有函数声明:

static int function1();

I have included this header file in abc.c and has defined the function and used it.

我已经在 abc.c 中包含了这个头文件,并且已经定义了函数并使用了它。

static int function1()
{
 < function definition>
}

After compiling I am getting warning:

编译后我收到警告:

warning: function1 declared static but never defined

How can I remove warning, without removing static. Thanks.

如何在不消除静电的情况下消除警告。谢谢。

采纳答案by hazzelnuttie

A static function can be declared in a header file, but this would cause each source file that included the header file to have its own private copy of the function, which is probably not what was intended.

静态函数可以在头文件中声明,但这会导致包含头文件的每个源文件都有自己的函数私有副本,这可能不是预期的。

Are u sure u haven't included the abc.hfile in any other .c files?

你确定你没有在任何其他 .c 文件中包含abc.h文件吗?

Because declaring a function as static, requires the function to be defined in all.c file(s) in which it is included.

因为将函数声明为静态函数,需要在包含它的所有.c 文件中定义该函数。

回答by Ehsan

Good practice: Declare static functions in the source file they are defined in (please also provide prototype), since that's the only file they are visible in.

好的做法:在定义它们的源文件中声明静态函数(请同时提供原型),因为这是它们唯一可见的文件。

This way, the function is only visible to that file, such visibility issues can reduce possible code conflict! So, just provide the prototype and the static function definition in the .c file. Do not include the static function in the header file; the .h file is for external consumption.

这样,函数只对那个文件可见,这样的可见性问题可以减少可能的代码冲突!因此,只需在 .c 文件中提供原型和静态函数定义。不要在头文件中包含静态函数;.h 文件供外部使用。

Duplicate: Static functions in C

重复:C 中的静态函数