C语言 C中的void和静态void函数有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41196027/
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 10:32:17  来源:igfitidea点击:

What is the difference between void and static void function in C?

cstatic

提问by msc

I have a two Cfiles.

我有两个C文件。

file1.c

文件1.c

int main()
{
  func(); 
  return 0;  
}

file2.c

文件2.c

static void func(void)
{
  puts("func called");
}

But, if I compile the above code with command cc file2.c file1.c, I got the below,

但是,如果我用 command 编译上面的代码cc file2.c file1.c,我会得到下面的,

undefined reference to `func'
collect2: error: ld returned 1 exit status

But, If I remove statickeyword inside file2.cand compile the above code with command cc file2.c file1.c, It's succesfully run.

但是,如果我删除file2.c中的static关键字并使用 command 编译上面的代码,它会成功运行。cc file2.c file1.c

So, I have a question, What is the difference between void and static void function in C?

所以,我有一个问题,C 中的 void 和 static void 函数什么区别?

回答by artm

What is the difference between void and static void function in C?

C中的void和静态void函数有什么区别?

The real question should be what is the difference between staticand non-staticfunction? (the return type voidis irrelevant, it can be intor anything else).

真正的问题应该是staticnon-static函数有什么区别?(返回类型void无关紧要,可以是int或其他任何类型)。

The statickeyword 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).

static关键字是有点过度使用。当它应用于函数时,意味着函数具有内部链接,即它的范围被限制在一个翻译单元内(简单地作为一个源文件)。

By default, function is non-static and has external linkage. The function can be used by a different source file.

默认情况下,函数是非静态的并且具有外部链接。该函数可由不同的源文件使用。

In your case, the error manifests itself because static funccannot be used in other source file.

在您的情况下,错误表现出来是因为static func不能在其他源文件中使用。



When should staticfunctions be used?

什么时候应该使用static函数?

staticfunctions are normally used to avoid name conflicts in bigger project. If you inspect Linux kernel source, example in drivers/netyou would see many static voidfunctions in there. Drivers are developed by different vendors and the usage of staticfunctions ensure that they can name the functions the way they want without worrying of name conflicts with other non-related driver developers.

static函数通常用于避免较大项目中的名称冲突。如果您检查 Linux 内核源代码,drivers/net您会static void在其中看到许多函数。驱动程序由不同的供应商开发,static函数的使用确保他们可以按照自己想要的方式命名函数,而不必担心与其他不相关的驱动程序开发人员的名称冲突。