所以,我有一个接口库,它包含一个单例类和另一个使用它的类。
假设它包含以下代码:
第一个月
struct Singleton {}; //< Singleton (actually it is in different file, but it really doesn't matter)
struct Object
{
public:
using Instance = std::pair<std::size_t, std::shared_ptr<Singleton>>;
template <typename T>
static std::shared_ptr<T> makeSingleton(T value)
{
inst = std::make_pair(typeid(T).hash_code(), std::make_shared<T>(value));
return std::static_pointer_cast<T>(inst.second);
}
private:
static Instance inst;
};
字符串
我也有两个地方,我想使用它:
main.cpp
的some_other_file.cpp
个
基本上,main.cpp
是一个可执行文件,而some_other_file.cpp
是另一个链接到main.cpp
可执行文件的库,因此结构如下所示:main.cpp
包含带有some_other_file.cpp
的库,该库包含接口“signleton.h”
当我尝试在main.cpp
中创建Object::Instance
的静态示例时,在MacOS上(在其他系统上一切正常),我得到链接错误。
错误代码:
Undefined symbol for architecture x86_64:
"Object::Instance", referenced from:
some_function_where_it_is_used() in some_other_file.cpp
...
型
我使用的是2016年的旧MacBook Air,所以这不是M1相关的问题。
我可以通过将Object::Instance
移动到some_other_file.cpp
来解决这个问题,但是由于我想让这个东西更容易找到,所以我想将它保留在main.cpp
中。
此外,我从来没有弄清楚这个问题的主要原因,我猜这是关于链接顺序和东西,但我不是很确定,因为它只发生在MacOS上。
1条答案
按热度按时间kkih6yb81#
macOS二进制可执行文件必须动态链接。操作系统和工具链根本不支持静态构建可执行文件。
二进制可执行文件可以动态地链接到静态构建的库。
除了内核扩展,但它们不依赖于任何东西,因为它们是独立的块。
参见https://developer.apple.com/forums/thread/706419