具有相同名称的两个静态变量(两个不同的文件),并在任何其他文件中外加一个静态变量 [英] Two static variables in same name(two different file) and extern one of them in any other file

查看:222
本文介绍了具有相同名称的两个静态变量(两个不同的文件),并在任何其他文件中外加一个静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个文件中将变量声明为静态,在另一个文件中进行extern声明-我认为这样做会在链接时产生错误,因为在任何对象中都不会看到extern变量,因为在另一个文件中声明的变量是与静态限定词.但是以某种方式,链接器(renesas)没有显示任何错误并创建了可执行文件.

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.

如果上述用例正确,那么在2个不同的文件中将2个变量声明为static,而在另一个文件中使用extern声明将其声明为static会发生什么?在这种情况下,将在2个不同的对象中创建2个不同的内存,但是哪个变量将链接到另一个变量在另一个文件中声明为extern(因为两个变量名相同)?

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;
}

推荐答案

答案可能是以您配置链接器的方式进行的.如果要链接库,则此处一切正常,并且file3.o模块的test_var引用为UNDEFINED.

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.

如果从这3个模块链接应用程序,则将失败,因为缺少main()例程定义和未解决的外部问题将被认为具有更少的弊端. :-)

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

只需进行检查,请在构建过程中检查适当的*.o模块符号表,然后检查最终结果.使用这种方法,您会发现奇怪的构建行为的原因.

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.

这篇关于具有相同名称的两个静态变量(两个不同的文件),并在任何其他文件中外加一个静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆