【发布时间】: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