使用静态成员时链接器错误
我在 Mac OS X 上使用 Qt 4.7 和 Cmake 2.8.3 以及 g++ 4.2.1。
在我的文件之一中使用静态或全局变量时,出现奇怪的链接器错误。 错误如下:
ld: duplicate symbol ColorTrail::calculateColorUniformLocation in CMakeFiles/GLBall.dir/src/DesktopMain.cpp.o and CMakeFiles/GLBall.dir/src/ColorTrail.cpp.o
collect2: ld returned 1 exit status
calculateColorUniformLocation 是类 ColorTrail 的静态成员...但它甚至根本没有在 DesktopMain.cpp 中使用!
这是我尝试过的: 重命名变量并不能解决问题。 将变量移出类并使其成为普通全局变量也无法修复该
问题 文件 ColorTrail.h:
#ifndef COLORTRAIL
#define COLORTRAIL 9
#include "GlobalConstants.h"
#include <vector>
using namespace std;
class ColorTrail
{
private:
//note that this is NOT a Q_OBJECT
static GLint calculateColorUniformLocation;
//omitted for brevity
};
GLint ColorTrail::calculateColorUniformLocation;
#endif
DesktopMain.cpp 使用类 ColorTrail,但不是静态的,并且从不引用该变量。
任何人都知道 Qt 可能出了什么问题/有类似的问题吗?
I'm using Qt 4.7 and Cmake 2.8.3 with g++ 4.2.1 on Mac OS X.
I'm getting a bizarre linker error when using static or global variables in one of my files.
Here's the error:
ld: duplicate symbol ColorTrail::calculateColorUniformLocation in CMakeFiles/GLBall.dir/src/DesktopMain.cpp.o and CMakeFiles/GLBall.dir/src/ColorTrail.cpp.o
collect2: ld returned 1 exit status
calculateColorUniformLocation is a static member of class ColorTrail... but its not even used in DesktopMain.cpp at all!
Here's what I've tried:
Renaming the variable doesn't fix the problem.
Moving the variable out of the class and just making it a plain global variable also doesn't fix it
The file ColorTrail.h:
#ifndef COLORTRAIL
#define COLORTRAIL 9
#include "GlobalConstants.h"
#include <vector>
using namespace std;
class ColorTrail
{
private:
//note that this is NOT a Q_OBJECT
static GLint calculateColorUniformLocation;
//omitted for brevity
};
GLint ColorTrail::calculateColorUniformLocation;
#endif
DesktopMain.cpp uses class ColorTrail, but not statically and never references the variable.
Anyone have any idea what could be wrong/had a similar problem with Qt?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在 cpp 文件中定义静态变量,而不是在头文件中。如果您在头文件中定义它,则包含此头文件的每个 cpp 文件都会获得自己的副本,因此链接器会抱怨重复的符号。
You need to define the static variable in cpp file and not in header file. If you define it in header file, every cpp file which includes this header will get its own copy hence linker complains about duplicate symbols.
静态数据成员必须在一个编译单元中显式定义
请参阅此链接:http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12
Static data members must be explicitly defined in exactly one compilation unit
See this link: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12