C中的void和静态void函数有什么区别? [英] What is the difference between void and static void function in C?
问题描述
我有两个 C 文件.
file1.c
int main()
{
func();
return 0;
}
file2.c
static void func(void)
{
puts("func called");
}
但是,如果我用命令 cc file2.c file1.c
编译上面的代码,我得到了下面的,
But, if I compile the above code with command cc file2.c file1.c
, I got the below,
undefined reference to `func'
collect2: error: ld returned 1 exit status
但是,如果我删除 file2.c 中的 static
关键字并使用命令 cc file2.c file1.c
编译上面的代码,它成功运行.
But, If I remove static
keyword inside file2.c and compile the above code with command cc file2.c file1.c
, It's succesfully run.
那么,我有一个问题,C 中的 void 和静态 void 函数有什么区别?
推荐答案
C 中的 void 和静态 void 函数有什么区别?
What is the difference between void and static void function in C?
真正的问题应该是static
和non-static
函数有什么区别?(返回类型 void
无关紧要,它可以是 int
或其他任何东西).
The real question should be what is the difference between static
and non-static
function? (the return type void
is irrelevant, it can be int
or anything else).
static
关键字有些过度使用.当应用于函数时,表示函数具有内部链接,即其范围仅限于翻译单元(仅作为源文件).
The static
keyword is somewhat over used. When it applies to function, it means that the function has internal linkage, ie its scope is limited to within a translation unit (simply as a source file).
默认情况下,函数是非静态的并且具有外部链接.该函数可以被不同的源文件使用.
By default, function is non-static and has external linkage. The function can be used by a different source file.
在您的情况下,错误表现出来是因为 static func
不能在其他源文件中使用.
In your case, the error manifests itself because static func
cannot be used in other source file.
什么时候应该使用静态
函数?
When should static
functions be used?
static
函数通常用于避免较大项目中的名称冲突.如果您检查 Linux 内核源代码,例如 drivers/net
中的示例,您会在其中看到许多 static void
函数.驱动程序由不同的供应商开发,static
函数的使用确保他们可以按照自己的方式命名函数,而不必担心与其他不相关的驱动程序开发人员的名称冲突.
static
functions are normally used to avoid name conflicts in bigger project. If you inspect Linux kernel source, example in drivers/net
you would see many static void
functions in there. Drivers are developed by different vendors and the usage of static
functions ensure that they can name the functions the way they want without worrying of name conflicts with other non-related driver developers.
这篇关于C中的void和静态void函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!