在全局头文件中声明全局变量? [英] Declaring a global in a global header file?

查看:619
本文介绍了在全局头文件中声明全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个头文件,让我们说Common.h,包括在几个项目的所有文件。基本上我想声明一个全局变量,例如:

  class MemoryManager; 
DLL_EXPORT MemoryManager * gMemoryManager;

当我这样做,我得到吨链接器错误说



class MemoryManager * gMemoryManager已定义。



:(?

解决方案

因为它是在每个编译文件中创建一个变量的单独副本,然后在链接阶段碰撞。记住,预处理器读取所有的头文件,并使一个大文件因此每次编译这个大文件时,会创建另一个相同的副本 gMemoryManager





在您的头文件

$中使用 extern b
$ b

  extern DLL_EXPORT MemoryManager * gMemoryManager; 


$ b b

在您的某个C ++文件中

  DLL_EXPORT MemoryManager * gMemoryManager; 



顺便说一句,我不知道DLL_EXPORT是什么,我只是假设它需要在两个地方。


I have a header file, lets say Common.h, that is included in all of the files over several projects. Basically i want to declare a global variable, e.g.:

class MemoryManager;
DLL_EXPORT MemoryManager* gMemoryManager;

When i do this i get tons of linker errors saying

class MemoryManager* gMemoryManager is already defined.

:(?

解决方案

As it is you are creating a separate copy of the variable in each compiled file. These are then colliding at the linking stage. Remember that the preprocessor reads in all the header files and makes one big file out of all of them. So each time this big file is compiled, another identical copy of gMemoryManager is created.

You need to use extern and define it in one non-header file.

In your header file

extern DLL_EXPORT MemoryManager* gMemoryManager;

In one of your C++ files

DLL_EXPORT MemoryManager * gMemoryManager;

By the way I have no idea what DLL_EXPORT does, I am just assuming it needs to go in both places.

这篇关于在全局头文件中声明全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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