Two static variables in same name(two different file) and extern one of them in any other file

StackOverflow https://stackoverflow.com/questions/20595371

  •  02-09-2022
  •  | 
  •  

Question

Declaring a variable as static in one file and do a extern declaration in another file - i thought this will give an error while linking as the extern variable will not be seen in any object, as the one which declared in other file was with qualifier static. But somehow the linker(renesas) didn't show any error and created executable.

If the above usecase was correct, what will happen if 2 variables be declared as static in 2 different files and another in another file with extern declaration? In this case 2 different memories will be created in 2 different objects, but which one of the variable will be linked for other variable was declared as extern in another file(as both the variable name are same)??

file1.c

static int test_var;
fn1()
{
   test_var = 1;
}    

file2.c

static int test_var;
fn2()
{
   test_var = 2;
}

file3.c

extern int test_var;
fn3()
{
   int x;
   x = test_var;
}
Était-ce utile?

La solution 2

The answer is probably in a way you have configured linker. If you are linking library everything will be OK here and file3.o module will have test_var reference as UNDEFINED.

If you're linking application from this 3 modules you will fail just because absence of main() routine definition and unresolved external will be considered even less evil. :-)

Just to check it please examine appropriate *.o modules symbol tables in your build process and then final result. Having such approach you will find the reason of your strange build behavior.

Autres conseils

In your example, file3.c has absolutely no access to variable test_var in either file1.c or file2.c. You should get a linking error if test_var is not declared within the scope of file3.c.

In file1.c and file2.c, the keyword static means the variable test_var is file scope. That means this variable only accessible in the the file where it's declared.

In the file3.c, the keyword extern means the variable is declared in other file.

When the compiler compile the file3.c, it will mark the variable test_var is in other object file, and doesn't care where is it. So this file can be compiled, and no errors occurred. But when the linker process this object files, it will found that no variable named as test_var can be link to file3, an error will be shown.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top