Linker error when using static members

2019-01-20 12:29发布

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?

2条回答
你好瞎i
2楼-- · 2019-01-20 13:05

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

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-20 13:17

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.

查看更多
登录 后发表回答