访问不同文件中的静态变量 [英] access static variables in different files

查看:111
本文介绍了访问不同文件中的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的头文件a1.h
a1.h

静态整数和;
int数据;

现在,我将这个a1.h包含在两个.cpp文件one.cpp和two.cpp中.
问题:
1.两个文件将共享sum变量,还是每个文件都有自己的副本?
2.两个文件中都包含a1.h时,总和与数据在内存分配方面有什么区别?
3.不要静态变量具有文件作用域,那么如何在其他文件中访问它呢?

I have a header file a1.h which looks like this
a1.h

static int sum;
int data;

Now i am including this a1.h in two .cpp files one.cpp and two.cpp.
Questions:
1.Will both the files share the sum variable or each will have its own copy?
2.what is the difference between sum and data in terms of memory allocation when a1.h is included in both the files?
3.dont static variables have a file scope, so how is it accessible in other files?

推荐答案

您真的不应该将这些内容放在头文件中.
就是说,我想您会收到data变量(多个符号定义)的链接器错误,而每个源文件将获得其自己的sum变量副本.
You really shouldn''t put that stuff in the header file.
That said, I guess you''ll get a linker error for the data variable (multiple symbol definitions) while each source file will get its own copy of the sum variable.


您能做的最好的就是尝试对其进行编译,然后看看会发生什么.
祝您好运
The best you can do is try and compile it, and see what happens.
Good luck,


1)每个文件都有其自己的"sum"变量,因此内存将被分配两次,因为它被声明为静态(文件作用域).
2)数据"具有全局作用域,因此两个* .c文件都可以编译,但链接器将失败,并出现多重定义的符号"类型错误.
3)无法在文件之间共享静态变量(除非您开始做一些真正不合常规的操作-例如,您可以计算出变量将最终存储在内存中的地址-但这只是普通的错误做法).此外,不需要共享静态变量和/或函数,因为将它们声明为静态的唯一原因是为了防止全局作用域.
4)您不应该在头文件中为此定义变量或任何对象.在头文件中声明它们,然后在c文件中实例化.
1) Each file will have its own "sum" variable, and hence memory will be allocated twice, because it is declared as static (file scope).
2) "data" has global scope hence both *.c files will compile but linker will fail with "multiply defined symbol"-type error.
3) There is no way to share static variables across files (unless you start doing something really unorthodox - e.g. you could work out the address in memory where the variable will end up - but this will be just plain bad practice). Moreover, there is no need to share static variables and/or functions as the only reason you declared them as static is to prevent global scope.
4) You should not define variables or any objects for that matter in header files. Declare them in header files and then instantiate in c files.


这篇关于访问不同文件中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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