Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

c++ - Linker error when using static members

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...