C中的静态函数 [英] Static functions in C

查看:100
本文介绍了C中的静态函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由* .h文件和* .c文件组成的软件模块。变量和函数声明位于* .h文件中,而函数定义位于* .c文件中。模块中的两个功能是辅助函数,它们不打算在模块之外使用。



使模块的用户清楚这个意图的最好方法是什么?



我试着声明函数 static ,但是在* .h文件中这样做会导致GCC编译器警告这些函数声明为静态但从未定义。如何将* .h和* .c文件视为不同的翻译单元,即使* .c文件使用 #include 指令来包含*。 h文件?



有没有解决这个问题的方法,它不涉及要执行的函数的声明 static 在* .c文件中,以及它们的定义?虽然这种解决方案确实起作用,但它破坏了我认为将头文件中的声明和定义保存在实现文件中的良好做法。

>


即使* .c文件使用#include指令来包含* .h文件,它是如何处理为不同的翻译单元的* .h和* .c文件?

标题通常也包含在其他源文件中。这是警告的原因。



如果您编译包括头文件在内的其他文件,则确实有一个函数声明为未定义。



好的做法是在它们定义的源文件中声明静态函数,因为这是它们可见的唯一文件。


I have a software module that consists of a *.h file and a *.c file. Variable and function declarations are located in the *.h file, whilst function definitions are located in the *.c file. Two functions within the module are helper functions that are not intended to be used outside of the module.

What is the best method of making this intent clear to users of the module?

I tried declaring the functions static, but doing so in the *.h file results in the GCC compiler warning that the functions are "declared static but never defined". How is it that the *.h and *.c files are treated as different translation units, even though the *.c file uses the #include directive to include the *.h file?

Is there a solution to this problem that does not involve placing the declarations of the functions that are to be made static in the *.c file, along with their definitions? Whilst this solution does work, it breaks what I thought was the good practice of keeping declarations in a header file and definitions in an implementation file.

解决方案

How is it that the *.h and *.c files are treated as different translation units, even though the *.c file uses the #include directive to include the *.h file?

The header is typically also included in other source files. That's the reason for the warning.

If you compile other files including the header, you indeed have a function declared that is not defined.

The good practice is to declare static functions in the source file they are defined in, since that's the only file they are visible in.

这篇关于C中的静态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆