• 4747阅读
  • 4回复

全局变量的问题 [复制链接]

上一主题 下一主题
离线ivoryxiong
 
只看楼主 倒序阅读 楼主  发表于: 2009-05-09
写的一个程序在bulid时发生了错误是全局变量的重复定义。我的做法是把全局变量在globalVars.h中定义,然后再每个要用的文件里包含该头文件,并把要用的加extern声明。
如globalVars.h
#ifndef GLOBALVARS_H
#define GLOBALVARS_H
const int MaxN = 100;
const double PI = 3.14159265;
const int iniHigh = 400 ;
const int iniWidth = 576 ;
const int perHour = 10;

ctyInf g_city[MaxN];
int g_city_num;

#endif // GLOBALVARS_H





inputblock.cpp:
#include "functions.h"
#include "dataStruct.h"
#include "globalVars.h"
#include <QtGui>
#include <cstring>
#include <cstdlib>
#include <ctime>

extern ctyInf g_city[MaxN];
extern int g_city_num;

错误是:
E:/DS/travelSys/inputBlock.cpp:39: multiple definition of `g_city_num'
E:/Qt/QtCreator/mingw/bin/../lib/gcc/mingw32/3.4.5/../../../../include/c++/3.4.5/bits/locale_facets.tcc:2497: multiple definition of `g_city'

请问这该怎样处理?


离线wader
只看该作者 1楼 发表于: 2009-05-10
将全局常量放在头文件中,全局变量放在源文件中,如下:

// GlobalVars.h
#ifndef GLOBALVARS_H
#define GLOBALVARS_H

const int MaxN = 100;
const double PI = 3.14159265;
const int iniHigh = 400 ;
const int iniWidth = 576 ;
const int perHour = 10;

extern double g_city[MaxN];
extern int g_city_num;

#endif // GLOBALVARS_H


// GlobalVars.cpp
#include "GlobalVar.h"

double g_city[MaxN];
int g_city_num;


需要使用的地方只需包含GlobalVars.h即可,也可以单独做外部声明
离线jorneyr

只看该作者 2楼 发表于: 2009-05-10
在源文件xxx.cpp中定义变量
const int MaxN = 100;
const double PI = 3.14159265;
const int iniHigh = 400 ;
const int iniWidth = 576 ;
const int perHour = 10;

然后在头文件xxx.h中声明一下外部使用
extern const int MaxN;
extern const double PI;
.............
离线ivoryxiong
只看该作者 3楼 发表于: 2009-05-10
在使用时直接包含XXX.h吗?我这样貌似不对
引用第2楼jorneyr于2009-05-10 04:10发表的  :
在源文件xxx.cpp中定义变量
const int MaxN = 100;
const double PI = 3.14159265;
const int iniHigh = 400 ;
const int iniWidth = 576 ;
.......
离线ivoryxiong
只看该作者 4楼 发表于: 2009-05-10
谢谢~这个方法很好用,也很容易明白~"第1楼wader于2009-05-10 02:21发表"话说大牛的踪迹都是这样的
引用第1楼wader于2009-05-10 02:21发表的  :
将全局常量放在头文件中,全局变量放在源文件中,如下:
// GlobalVars.h
#ifndef GLOBALVARS_H
#define GLOBALVARS_H
.......
快速回复
限100 字节
 
上一个 下一个