C++静态成员变量必须在类的定义之外进行声明 (error LNK2001: unresolved external symbol)

Posted scruffybear

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++静态成员变量必须在类的定义之外进行声明 (error LNK2001: unresolved external symbol)相关的知识,希望对你有一定的参考价值。


文章目录

小结

C++的Visual Studio工程返回error LNK2001的错误,以及在调试运行的过程中出现了Unhandled exception (ntdll.dll)的问题,对这两个问题进行了解决。

问题和解决

Error LNK2001错误

参考描述:
​​​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. ​

也就是非静态数据成员应该定义在类的外面,需要在调用这个类的命名空间之内进行一次定义声明。 通常的做法是的把这个非静态数据成员定义在C++程序文件(*.cpp)中。

例如在一个并文件中(*.h),有一个类中定义了如下静态成员变量:

static RosbridgeWsClient rosBridgeConn;

那么需要在相应的*.cpp中定义声明这个静态成员变量。否则会报错:
​​​LNK2001 unresolved external symbol "private: static class......​

具体解决问题的定义方法如下:

RosbridgeWsClient RoboticArmJetmax::rosBridgeConn("xxx.xx.xx.xx:9090");

修改后测试通过没问题。

Unhandled exception (ntdll.dll)

在程序运行的过程中会报错:​​Unhandled exception at 0xxcxxxxxxx (ntdll.dll) in xxx.exe: 0x12345678: Access violation writing location 0x-xxxxxxxx​

具体的问题可能是使用的库的问题,参考:​​Unhandled exception at 0x77081d76 (ntdll.dll) in Stereo Vision.exe: 0xC0000005: Access violation writing location 0x00000014​

​工程属性-> C/C++ -> Code Generation -> Run Time Library -> Multi-threaded Debug DLL (/MDd)​

进行了修改后再也没出现过这个问题了。

参考

​C++类静态成员变量导致报错error LNK2001: unresolved external symbol "private: static class​​​​Stackoverflow: error LNK2001: unresolved external symbol "private: static class​​​​Unhandled exception at 0x77081d76 (ntdll.dll) in Stereo Vision.exe: 0xC0000005: Access violation writing location 0x00000014​


以上是关于C++静态成员变量必须在类的定义之外进行声明 (error LNK2001: unresolved external symbol)的主要内容,如果未能解决你的问题,请参考以下文章

C++静态成员变量必须在类的定义之外进行声明 (error LNK2001: unresolved external symbol)

C++中类里面定义 静态成员变量的问题

静态常量非整形成员变量的初始化问题

为啥我不能只用前向声明 C++ 声明一个类的静态成员?

static, const

C++入门静态成员详解(定义实现原理使用注意事项)