C++ gcc/g++;以及全局变量的多个定义
我有几个.h/.cpp文件,每个文件都应该有名为“common.h/common.cpp”的文件,因为我在其余文件中重复使用了它的定义。common.h文件定义了一些全局变量 我在Linux和GCC4.4.7下工作 Compuler的工作还行,但g++链接器会抱怨许多情况,如:C++ gcc/g++;以及全局变量的多个定义,c++,gcc,g++,C++,Gcc,G++,我有几个.h/.cpp文件,每个文件都应该有名为“common.h/common.cpp”的文件,因为我在其余文件中重复使用了它的定义。common.h文件定义了一些全局变量 我在Linux和GCC4.4.7下工作 Compuler的工作还行,但g++链接器会抱怨许多情况,如: build/Debug/GNU-Linux-x86/StoreData2/spacewx.o:(.data+0x200): multiple definition of `nmdata::names` build/Deb
build/Debug/GNU-Linux-x86/StoreData2/spacewx.o:(.data+0x200): multiple definition of `nmdata::names`
build/Debug/GNU-Linux-x86/StoreData2/StoreData2.o:(.data+0x200): first defined here
因此,我没有得到一个成功的建设。请建议如何消除此错误,并保留这些全局变量。我只使用函数式编程(使用C++库,如Boost)和至今没有自己的命名空间/对象。 < P>让我们假设全局头是(<代码> Global .H./Cube >): 如果您有两个源文件,包括
global.h
:a.cpp
和b.cpp
,如下所示:
a.cpp
#include "global.h"
/* some source */
#include "global.h"
/* some source */
int g_a;
/* some source */
int g_a;
/* some source */
#include "global.h"
int g_a;
/* some source */
b.cpp
#include "global.h"
/* some source */
#include "global.h"
/* some source */
int g_a;
/* some source */
int g_a;
/* some source */
#include "global.h"
int g_a;
/* some source */
预处理后,它们将如下所示(包括的文件将展开):
a.cpp
#include "global.h"
/* some source */
#include "global.h"
/* some source */
int g_a;
/* some source */
int g_a;
/* some source */
#include "global.h"
int g_a;
/* some source */
b.cpp
#include "global.h"
/* some source */
#include "global.h"
/* some source */
int g_a;
/* some source */
int g_a;
/* some source */
#include "global.h"
int g_a;
/* some source */
因此,如果编译这些源文件,全局变量int g_a
将在两个目标文件中定义。因此链接器会抱怨多个定义
要解决此问题,您需要在标题中添加extern
关键字extern
关键字告诉编译器变量是在其他地方定义的。因此,不会将新的全局对象条目写入对象文件
更改global.h
,如下所示:
#ifndef _GLOBAL_H
#define _GLOBAL_H
extern int g_a;
#endif
因此,将不会有int g_a
条目写入对象文件。但这会导致链接中出现未定义的符号错误。要克服这一问题,请在a.cpp
或b.cpp
中定义int g_a
,但不能同时在两者中定义
b.cpp
#include "global.h"
/* some source */
#include "global.h"
/* some source */
int g_a;
/* some source */
int g_a;
/* some source */
#include "global.h"
int g_a;
/* some source */
程序中的每个变量或函数只能在一个编译单元中定义一次。如果在多个编译单元中定义任何内容,通常会出现链接错误,正如您所看到的那样,尽管官方说法,这是未定义的行为,因此编译器可能不会给出诊断,您的程序只会出现错误
<>你可以在你的程序中有多个事物的声明,所以一般情况下,你会设置所有的东西,这样你的头文件只有声明,所有的定义都在.CPP文件中。你最小的例子在哪里?你真的不认为任何源DOE可能是相关的吗?考虑使用<代码> Extn< <代码>关键字。如果你能给我们一些最简单的代码,我可以给你一个很好的答案。@AskarIbragimov:那又怎样?发帖。@AskarIbragimov这不是态度的问题。这是关于遵守网站的规则。