全局变量和范围 - C ++ [英] Global variables and scope - C++

查看:156
本文介绍了全局变量和范围 - C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题在做一个全局变量的工作。我使用Visual Studio 2008和标准C ++。

I am having small problem in making a global variable works. I am using Visual Studio 2008 and standard C++.

我有两个项目,一个是静态库,第二个是使用这个库的测试程序。我在global.h中有一个全局变量,例如

I have two projects, one is a static library and second one is a test program which uses this library. I have a global variable in global.h like

#ifndef GLOBAL_H
#define GLOBAL_H

#include <string>

extern std::string globalWord;

#endif // GLOBAL_H!



我有一个global.cpp,我在初始化这个变量。这个变量在我的库项目中使用。我从测试项目中设置一个值到这个变量,但是这个值没有反映在库项目中。

I have a global.cpp where I am initializing this variable. This variable is used inside my library project. I am setting a value to this variable from the test project, but that value is not getting reflected in the library project.

我已经调试,它显示测试项目中的新值,但是当控件到达库项目时,此变量值显示为空。所以这个全局变量的范围只限于它属于的项目?

I have debugged and it shows the new value in test project, but when the control reaches the library project, this variable value shows empty. So is this global variable's scope only limited to the project where it belongs to?

还是有更好的方法吗?我不想在我的库中修改我的函数或构造函数的参数来传递这个值。

Or is there a better way to do this? I don't want to modify my function or constructor parameters in my library to pass this value.

任何帮助将是巨大的。

编辑:

以下是在global.cpp中声明此变量的方法

Here is how this variable is declared in global.cpp

#include <string>
#include "../global.h"

std::string globalWord = "";

这是我在我的图书馆中使用的方式

This is how I used it in my library

#include "../global.h"
string text = globalWord;

感谢

推荐答案

不要使用全局变量。只是不要。更好的是,如果你有全局可访问的数据,使用一个全局函数,将返回globalWord,如下:

Don't use global variables. Just don't. Much better, if you HAVE to have globally accessible data, is to use a global function which will return globalWord, like this:

std::string globalWord()
{
    static std::string word("Hi Mom");
    return word;
}

这样可以避免初始化顺序问题(参见Effective C ++ item#4)。

This saves you from initialization order issues (read Effective C++ item #4).

这篇关于全局变量和范围 - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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