Linker error when using static members(使用静态成员时的链接器错误)
问题描述
我在 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.
这篇关于使用静态成员时的链接器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用静态成员时的链接器错误


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01