in C/C++

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

Write a Comment

Comment