undefined reference to CPUAllocatorSingleton::instance
它发生的原因是你声明了 CPUAllocatorSingleton
类中的 instance
变量,但没有提供它的定义。
这个错误是链接器无法找到 CPUAllocatorSingleton::instance
的定义。它发生的原因是你声明了 CPUAllocatorSingleton
类中的 instance
变量,但没有提供它的定义。
具体来说,错误信息显示:
-
undefined reference to
CPUAllocatorSingleton::instance
:编译器找不到CPUAllocatorSingleton::instance
的定义。 -
**relocation against
_ZN21CPUAllocatorSingleton8instanceE'**:这表明链接器正在试图将代码链接到
CPUAllocatorSingleton::instance`,但是找不到该变量的实际位置。
解决方法:
-
定义
instance
变量:你在
CPUAllocatorSingleton
类中声明了instance
变量,但它需要在.cpp
文件中进行定义。可以像下面这样定义instance
:// 在头文件中声明 class CPUAllocatorSingleton { public:static std::shared_ptr<CPUAllocator> getInstance();private:static std::shared_ptr<CPUAllocator> instance; // 声明静态成员变量 };// 在 .cpp 文件中定义 std::shared_ptr<CPUAllocator> CPUAllocatorSingleton::instance = nullptr; // 定义静态成员变量
-
静态成员变量的定义:
静态成员变量需要在类外部进行定义,即使它已经在类内声明了。否则,编译器就找不到该变量的地址,从而导致链接错误。