转自:https://blog.youkuaiyun.com/Owen_Suen/article/details/104762593
今天在为Qt+OpenCV项目添加工具类Class Helper的时候,静态变量和静态函数总会导致报错
-
Severity Code Description Project File Line Suppression State -
Error LNK2001 unresolved external symbol "private: static class QColor * Helper::lineColor" (?lineColor@Helper@@0PEAVQColor@@EA) QtOpenCVProjE2 E:\VSProj\QtOpenCVProjE2\QtOpenCVProjE2\Helper.obj 1
如下图所示:
当仅有静态变量,而不对静态变量做读写时候并不会报错;但是当改动其值时候,就会报错LNK2001

在参考文章《error LNK2001:未解析的外部符号“private:static class(error LNK2001: unresolved external symbol "private: static class)》(https://www.it1352.com/476238.html)之后,找到了原因
需要在源代码文件.cpp文件中添加一句静态非常量成员变量的定义
QColor* Helper::lineColor;
如图所示:

static, but non-const data members should be defined outside of the class definition and inside the namespace enclosing the class. The usual practice is to define it in the translation unit (*.cpp) because it is considered to be an implementation detail. Only static and const integral types can be declared and defined at the same time (inside class definition).
【来自上述参考文章《error LNK2001:未解析的外部符号“private:static class(error LNK2001: unresolved external symbol "private: static class)》(https://www.it1352.com/476238.html)】
静态但非常量成员变量应该在类定义之外,该类所属的命名空间之内,进行定义。
一般惯例将其定义在翻译单元(即.cpp文件)中,引起被视为实现细节。
只有静态常量整型变量才能在同一处声明与定义(即在类内定义)。

本文详细介绍了在Qt+OpenCV项目中遇到LNK2001未解析外部符号错误的原因及解决方案。通过正确地在.cpp文件中定义静态变量,可以避免此类编译链接错误。
439





