如何在C ++中从一个文件访问静态变量到另一个文件 [英] How Can I Access Static Variables From One File To Anothe File In C++

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

问题描述

我们正在开发visual studio中的代码如何从一个文件访问静态变量到另一个文件

we are developing code in visual studio how can i access static variable from one file to another file

推荐答案

你没有。 static (或者现在通常使用的是匿名命名空间中的变量)是制作一个变量可从单个翻译单元访问。因此,如果有人将变量装饰为 static ,那么他们的设计要么有缺陷(他们没有意识到其他地方需要这些信息)或者他们真的没有想要摆弄那个变量的内容。



如果你真的需要访问 static 那么你可以删除 static 装饰以使其成为全局装饰并在其他翻译单元中将其声明为 extern 。但是请确保你知道你正在做什么,因为可能有充分的理由让这些数据 static - 两个例子可能是它不是线程安全的,或者他们打算移动其他地方的数据块。
You don't. The point of static (or as is usually used these days, variables in anonymous namespaces) is to make a variable accessible from a single translation unit. So if someone's decorated a variable as static then their design either had a flaw in it (they didn't realise the information would be needed somewhere else) or they really don't want you fiddling about with the contents of that variable.

If you really need access to the static then you can remove the static decoration to make it a global and declare it as extern in the other translation unit. However make sure you know what you're doing as there might be a good reason for making this data static - two example could be it's not thread safe or they intend to move the lump of data somewhere else.


这通常使用包含的头文件和其中的extern声明来完成。在其中一个文件中,您还应该定义此变量。

例如,这里有解释: http://www.geeksforgeeks.org/understanding-extern-keyword-in-c [ ^ ]。



您需要了解单独编译的背景;编译器做了什么以及链接器做了什么。



使用C ++,将所有内容都包含在类(或枚举类型)中是个好主意。在某种程度上,这是个人品味的问题。



-SA
This is normally done using included header file and an "extern" declaration in it. In one of the file, you should also define this variable.
This is explained, for example, here: http://www.geeksforgeeks.org/understanding-extern-keyword-in-c[^].

You need to understand the background of separate compilation; what the compiler does and what the linker does.

With C++, it would be a good idea to have everything in classes (or enumeration types). To certain extent, this is a matter of personal taste.

—SA


这篇关于如何在C ++中从一个文件访问静态变量到另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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