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

Viewed 79

1.c

static int test(){
 return 5;
}

int main(){
 return test();
}

2.c

int test(){
 return 6;
}

Above code is compiled fine with gcc 1.c 2.c and 5 is returned as expected. 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?

1 Answers

The compiler will ensure that uses of test in 1.c refer only to the test defined in 1.c.

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. 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). The way an identifier declared in one translation unit refers to a function or object defined in another translation unit is through linkage.

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. (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.)

In the file 2.c, the definition int test() {…} defines test with file scope and external linkage. This means that uses of test in other translation units can refer to the test defined in 2.c. However, that occurs in another translation unit only when test is declared with external linkage in that unit. Since the declaration of test in 1.c has internal linkage, it is not linked to any external definition.

Related