【问题标题】:C++ global variable in multiple files多个文件中的 C++ 全局变量
【发布时间】:2014-03-21 19:16:42
【问题描述】:

我有一个类按钮,其中包括一个管理按钮的类 ButtonManager。

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

但是,这两个窗口占用了很多行,因此我决定将其拆分为多个 .cpp 文件,我只是从 main 中调用内容。

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

主要问题是,ButtonManager 有一个全局变量,并且在编译时说符号已经定义。

示例代码:

a.h(就好像它是 Button Manager 头文件一样):

#ifndef _ABC_
#define _ABC_

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

#endif

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

#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();
}

当我尝试编译它时,编译器会报错:

1>side.obj : error LNK2005: "struct A a" (?a@@3UA@@A) already defined in DynamicDispatch.obj 1>H:\Microsoft Visual Studio 11.0\example\Debug\dynamicdispatch.exe : fatal error LNK1169: one or more multiply defined symbols found

感谢所有帮助

【问题讨论】:

  • 我搜索过,我知道extern 关键字,但是您如何将extern 关键字应用于以这种方式定义的变量?我只是到目前为止,如果我从main.cpp 中删除#include "abc.h" 它可以工作,但是我不能在main.cpp 中使用struct A

标签: c++ visual-studio-2012


【解决方案1】:

a.h 中声明变量为

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

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

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

【讨论】:

  • 谢谢你,这行得通,即使我认为它可以只输入一次,但看起来那是不可能的;编辑:mainhehe 中有错字
  • @0x499602D2 我修复了它。它说mian
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-25
  • 2013-04-11
  • 1970-01-01
  • 2021-11-14
相关资源
最近更新 更多