问题描述
我在 Mac OS X 上使用 Qt 4.7 和 Cmake 2.8.3 以及 g++ 4.2.1.
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 是类 ColorTrail 的静态成员...但它甚至根本没有在 DesktopMain.cpp 中使用!
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
文件 ColorTrail.h:
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 使用类 ColorTrail,但不是静态的,也从不引用变量.
DesktopMain.cpp uses class ColorTrail, but not statically and never references the variable.
有谁知道 Qt 有什么问题/有类似的问题吗?
Anyone have any idea what could be wrong/had a similar problem with Qt?
推荐答案
您需要在 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.
这篇关于使用静态成员时的链接器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!