静态工厂模式编译失败:Object静态成员未定义引用错误
解决MinGW64编译静态工厂模式时的未定义引用错误
嘿,我瞅你在Windows下用MinGW64编译静态工厂模式的代码时碰到了链接错误,报错信息是:
main.cpp:(.rdata$.refptr._ZN6Object17registryFormatMapB5cxx11E[.refptr._ZN6Object17registryFormatMapB5cxx11E]+0x0): undefined reference to `Object::registryFormatMap[abi:cxx11]'
先看看你给出的代码:
object.h
#ifndef TESTFACTORYMETHOD_OBJECT_H #define TESTFACTORYMETHOD_OBJECT_H #include <string> #include <unordered_map> #include <functional> class Object; using RegistryFormatMap = std::unordered_map<std::string, std::string>; using RegistryConstructorMap = std::unordered_map<std::string, std::function<Object*(const std::string &)>>; class Object { public: static RegistryFormatMap registryFormatMap; static RegistryConstructorMap registryConstructorMap; private: }; #endif //TESTFACTORYMETHOD_OBJECT_H
apple.h
#ifndef TESTFACTORYMETHOD_APPLE_H #define TESTFACTORYMETHOD_APPLE_H #include "object.h" class Apple : public Object{ public: constexpr static char m_name[6] = "Apple"; std::string m_test_val; class Factory { public: Factory(){ std::string temp = m_name; Object::registryFormatMap[temp] = "test_apple"; Object::registryConstructorMap[temp] = ([](const std::string &in) -> Apple * { return new Apple(in); }); } }; static Factory factory; explicit Apple(const std::string& str) { m_test_val = str; } private: }; #endif //TESTFACTORYMETHOD_APPLE_H
main.cpp
#include <iostream> #include "object.h" int main() { for(const std::pair<std::string, std::string>& pair : Object::registryFormatMap) { std::cout << pair.second << std::endl; } return 0; }
问题原因
这个错误的核心是C++类的静态成员变量只在头文件里声明了,但没有在全局作用域下定义。你在Object类里声明了registryFormatMap和registryConstructorMap这两个静态成员,但链接器找不到它们的实际存储实体,所以抛出了未定义引用的错误。另外还有个隐藏问题:Apple类里的静态factory成员也没定义,就算前面的错误解决了,你的注册逻辑也不会执行,main里啥也打不出来。
解决方案
- 创建
object.cpp定义Object的静态成员
新建一个object.cpp文件,内容如下:
#include "object.h" // 定义Object类的静态成员变量,分配存储空间 RegistryFormatMap Object::registryFormatMap; RegistryConstructorMap Object::registryConstructorMap;
- 创建
apple.cpp定义Apple的静态factory
再新建apple.cpp文件:
#include "apple.h" // 定义Apple的静态Factory对象,触发构造函数里的注册逻辑 Apple::Factory Apple::factory;
- 编译时包含所有cpp文件
用MinGW64编译的时候,要把所有相关的cpp文件都加进去,比如执行命令:
g++ main.cpp object.cpp apple.cpp -o test_factory
这样编译链接就能顺利完成,运行生成的test_factory.exe就能看到输出test_apple了。
内容的提问来源于stack exchange,提问作者Krupip
相关产品推荐
相关产品推荐

