使用静态成员时链接器错误 [英] Linker error when using static members

查看:81
本文介绍了使用静态成员时链接器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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!

ve tried:
重命名变量并不能解决问题。
将变量移出类,只是使它成为一个普通的全局变量也不能解决它。

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.

这篇关于使用静态成员时链接器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆