多个文件中的全局变量


74

我有两个源文件需要访问一个公共变量。做这个的最好方式是什么?例如:

source1.cpp:

int global;

int function();

int main()
{
    global=42;
    function();
    return 0;
}

source2.cpp:

int function()
{
    if(global==42)
        return 42;
    return 0;
}

全局变量的声明应该是静态的,外部的,还是应该在两个文件都包含的头文件中,等等?


这个问题可能重复。
fredoverflow

8
重新编写代码以使用除全局变量以外的其他内容-或将问题重新标记为“ C”。当我需要C ++中的全局变量时,通常使它成为可通过访问器方法公开读取的类的静态成员。如果可以缩小范围,以便仅内部类成员使用访问器,那就更好了。很少有变量是真正的“全局”变量。
史蒂夫·汤森

1
取决于您要做什么
Chubsdad 2010年

function()这两种来源也很常见,需要相同的待遇。关于global“最佳方式”,根本这样做。eetimes.com/discussion/break-point/4025723/A-pox-on-globals
Clifford

Answers:


122

全局变量应extern在两个源文件都包含的头文件中声明,然后仅在这些源文件之一中定义:

普通

extern int global;

source1.cpp

#include "common.h"

int global;

int function(); 

int main()
{
    global=42;
    function();
    return 0;
}

source2.cpp

#include "common.h"

int function()
{
    if(global==42)
        return 42;
    return 0;
}

3
如果您需要更多信息和解释,请访问以下
网址

如何使用QString,即时通讯 extern QString ciclo_actual;用于全局变量,我可以在任何文件上定义它,但编译器始终拖延QString does not name a type
lightshadown

16

您添加一个“头文件”,该文件描述模块source1.cpp的接口:

source1.h

#ifndef SOURCE1_H_
#define SOURCE1_H_

extern int global;

#endif

source2.h

#ifndef SOURCE2_H_
#define SOURCE2_H_

int function();

#endif

并在每个使用此变量的文件中添加#include语句,并在(重要)变量中定义该变量。

source1.cpp

#include "source1.h"
#include "source2.h"

int global;     

int main()     
{     
    global=42;     
    function();     
    return 0;     
}

source2.cpp

#include "source1.h"
#include "source2.h"

int function()            
{            
    if(global==42)            
        return 42;            
    return 0;            
}

虽然没有必要,但我建议为该文件使用名称source1.h,以表明它描述了模块source1.cpp的公共接口。同样,source2.h描述了source2.cpp中的公共可用内容。


1

在一个文件中,将其声明为source1.cpp,在第二个文件中,将其声明为

extern int global;

当然,您确实不想这样做,应该发布有关您要实现的目标的问题,以便此处的人可以为您提供实现该目标的其他方法。


1
您应该实现使编译器为每个编译单元获取相同的extern声明,该声明需要该声明。当将外部变量散布到需要外部访问变量,函数的所有文件时,...很难使它们保持同步。这就是为什么:不要在使用中的.cpp文件中声明extern。
哈珀2010年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.