简体   繁体   English

static 和非静态 function 在 2 个编译单元中具有相同的名称

[英]static and non-static function with same name in 2 compilation units

1.c 1.c

static int test(){
 return 5;
}

int main(){
 return test();
}

2.c 2.c

int test(){
 return 6;
}

Above code is compiled fine with gcc 1.c 2.c and 5 is returned as expected.上面的代码用gcc 1.c 2.c5按预期返回。 My question is, will the linker choose test in 1.c at all times or its unspecified behaviour and test in 2.c could be chosen as well?我的问题是,linker 是否会始终选择1.c中的test ,或者其未指定的行为和2.c中的test也可以选择?

The compiler will ensure that uses of test in 1.c refer only to the test defined in 1.c .编译器将确保 1.c 中的test使用1.c 1.c中定义的test

The definition static int test() {…} declares test with file scope (per C 2018 6.2.1 4) and internal linkage (per C 2018 6.2.2 3). The definition static int test() {…} declares test with file scope (per C 2018 6.2.1 4) and internal linkage (per C 2018 6.2.2 3).

Scope is where in the source code an identifier is visible. Scope是在源代码中可见标识符的位置。 File scope is the largest scope in C—a declaration cannot make an identifier visible outside its translation unit (the source file being compiled with all included headers).文件 scope 是 C 语言中最大的 scope — 声明不能使标识符在其翻译单元之外可见(正在编译的源文件包含所有包含的头文件)。 The way an identifier declared in one translation unit refers to a function or object defined in another translation unit is through linkage .在一个翻译单元中声明的标识符引用另一个翻译单元中定义的 function 或 object 的方式是通过链接

Since static int test() {…} declares test with internal linkage, uses of test within its scope refer to that definition, the one internal to the translation unit.由于static int test() {…}声明test具有内部链接,因此在其 scope 中使用test指的是该定义,即翻译单元内部的定义。 (There is an exception if another declaration of test appears inside a function. An inner declaration can hide an outer declaration and refer to a different entity. There are certain rules about such declarations that I will not cover in this answer.) (如果另一个test声明出现在 function 中,则有一个例外。内部声明可以隐藏外部声明并引用不同的实体。关于此类声明的某些规则我不会在此答案中介绍。)

In the file 2.c , the definition int test() {…} defines test with file scope and external linkage .在文件2.c中,定义int test() {…}使用文件 scope 和外部链接定义test This means that uses of test in other translation units can refer to the test defined in 2.c .这意味着在其他翻译单元中使用test可以参考2.c中定义的test However, that occurs in another translation unit only when test is declared with external linkage in that unit.但是,仅当在该单元中使用外部链接声明test时,才会在另一个翻译单元中发生这种情况。 Since the declaration of test in 1.c has internal linkage, it is not linked to any external definition.由于1.c中的test声明具有内部链接,因此未链接到任何外部定义。

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

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