Linker error when using static members

梦想与她 提交于 2019-11-27 08:11:14

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/8612206/linker-error-when-using-static-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!