多个文件中的C++全局变量 [英] C++ global variable in multiple files

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

问题描述

我有一个 Button 类,其中包括一个 ButtonManager 类,用于管理按钮.

I have a Class Button, that includes a class ButtonManager, which managers buttons.

然后我有 2 个处理事情的函数,1 个像带有几个按钮的登录窗口,第二个是游戏菜单本身,里面也有按钮.

Then I have 2 functions that handle things, 1 is like login window with few buttons, the second one is the game menu itself, which also has buttons in it.

然而,这两个窗口占用了相当多的行,所以我决定将其拆分为多个 .cpp 文件,我只在其中调用 main 中的东西.

However, the two windows take quite a lot of lines, and so I decided to split it to multiple .cpp files, where I just call stuff from main.

问题是,我需要在 .cpp 中都包含按钮类,并且主 cpp 和辅助 cpp 还包含一些 dummy.h,其中包含渲染菜单的通用函数的声明.

The problem is, I need to include the button class in both .cpps, and main and the secondary cpp also include some dummy.h which contains the declaration of the common function rendering the menu.

主要问题是,ButtonManager 有一个全局变量,并且在编译时表示该符号已定义.

The main issue is, that the ButtonManager has a global variable and when compiling it says that the symbol is already defined.

示例代码:

a.h(就像按钮管理器头文件一样):

a.h(acts as if it was the Button Manager header file):

#ifndef _ABC_
#define _ABC_

struct A{
    int b;
}a = A();

#endif

side.h(假设这是用于主游戏窗口):

side.h(lets say this is for main game window):

#ifndef _SIDE_H_
#define _SIDE_H_

int callSomething();

#endif    //_SIDE_H_:

side.cpp:

#include "side.h"
#include "abc.h"

#include <iostream>

int callSomething()
{
    std::cout << a.b << "\n";
    return a.b;
}

main.cpp:

#include "abc.h"
#include "side.h"
#include <iostream>

int main()
{
    callSomething();
    std::cin.get();
}

当我尝试编译它时,编译器抱怨:

When I try to compile it, the compiler complains:

1>side.obj : error LNK2005: "struct A a" (?a@@3UA@@A) 已经在 DynamicDispatch.obj 中定义1>H:\Microsoft Visual Studio 11.0\example\Debug\dynamicdispatch.exe:致命错误 LNK1169:找到一个或多个多重定义的符号

感谢所有帮助

推荐答案

a.h中将变量声明为

struct A{
    int b;
};
extern struct A a;

然后在 main.cpp 中定义一次:

Then in main.cpp define it once:

struct A a;
int main()
{
    //...
}

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

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