在目标 c++ 中声明全局变量时出错?
每当我将全局变量 id theScene 放入 .mm 文件时,我都会收到错误 Command/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-g++-4.2 failed with exit code 1
。它适用于 .m 文件,但稍后我需要 .mm 来实现 box2d。另外,我认为真正的错误在于:
ld:/Users/sgupta100/Documents/TheifGame/build/TheifGame.build/Release-iphonesimulator/TheifGame.build/Objects-normal/i386/HelloWorldScene中的重复符号_theScene。和/Users/sgupta100/Documents/TheifGame/build/TheifGame.build/Release-iphonesimulator/TheifGame.build/Objects-normal/i386/TheifGameAppDelegate.o
我不知道这到底是什么意思,有人可以解释一下吗?
I get the error Command/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-g++-4.2 failed with exit code 1
whenever I put a global variable id theScene in a .mm file. It works with a .m file but I need .mm for box2d implementation later on. Also, I think the real error resides here:
ld: duplicate symbol _theScene in /Users/sgupta100/Documents/TheifGame/build/TheifGame.build/Release-iphonesimulator/TheifGame.build/Objects-normal/i386/HelloWorldScene.o and /Users/sgupta100/Documents/TheifGame/build/TheifGame.build/Release-iphonesimulator/TheifGame.build/Objects-normal/i386/TheifGameAppDelegate.o
I do not know what this really means so can someone explain?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该变量是否在标头中的某处声明?如果是这样,声明是否使用
extern
关键字?如果没有,编译器将为#include
作为标头的每个编译单元(.m、.mm、.c、.cpp 等)发出一个符号。如果标头不是问题,则“HelloWorldScene”和“TheifGameAppDelegate”编译单元中的某些内容正在生成 theScene 符号。要么变量在两者中定义,要么其他东西(例如函数)碰巧具有相同的名称。
如果不发布您的代码或其他详细信息,我就无法告诉您有关此问题的更多信息。
更新:跨多个文件使用全局变量的正确方法是在标头中将变量声明为
extern
(有条件地使用extern "C"
当使用 (Objective-)C++ 编译时,并且该变量还需要可以从 (Objective-)C 访问,然后在 .m、.mm、.c 或 .cpp 文件中定义一次,无需外部
当然,所有需要访问该变量的文件都必须包含该标头。Is this variable declared in a header somewhere? If so, does the declaration use the
extern
keyword? If it doesn't, the compiler will emit a symbol for each compilation unit (.m, .mm, .c, .cpp, etc.) that#include
s the header.If the header isn't a problem, something in both your "HelloWorldScene" and "TheifGameAppDelegate" compilations unit is producing a theScene symbol. Either the variable is defined in both, or something else, such as a function, happens to have the same name.
Without posting your code or other details, there's no more I can tell you about this issue.
Update: the correct way to use global variables across multiple files is to declare the variable as
extern
in a header (conditionally useextern "C"
when compiling with (Objective-)C++ and the variable also needs to be accessible from (Objective-)C. Then define it exactly once in a .m, .mm, .c or .cpp file without theextern
and possibly with an initialiser. The header must of course be included by all files that require access to the variable.