gpt4 book ai didi

c++ - weak_import 生成链接器错误

转载 作者:行者123 更新时间:2023-11-28 06:40:27 26 4
gpt4 key购买 nike

为什么在 OSX 10.8 下编译时下面的代码没有链接?我怎样才能让它链接以便它可以在 10.8 和 10.9 上工作?我正在使用 clang++ 5.1。

// MyFile.cc
// Compile with: clang++ MyFile.cc -framework ApplicationServices

#include <ApplicationServices/ApplicationServices.h>
#include <iostream>

extern "C" CFStringRef kAXTrustedCheckOptionPrompt __attribute__ ((weak_import));
extern "C" Boolean AXIsProcessTrustedWithOptions (CFDictionaryRef options) __attribute__ ((weak_import));

static bool IsSupported (void)
{
return AXIsProcessTrustedWithOptions ?
AXIsProcessTrustedWithOptions (NULL):
AXAPIEnabled() || AXIsProcessTrusted();
}

int main (void)
{
std::cout << (IsSupported() ? "SUPPORTED\n" : "NOT SUPPORTED\n");
return 0;
}

注意:一切都在 10.9 中工作,二进制文件在 10.8 中工作。

最佳答案

弱链接仍然需要链接。您链接到的库或框架仍然必须定义符号。在 10.8 SDK 中,ApplicationServices 框架没有定义 AXIsProcessTrustedWithOptions 符号。

我至少可以想到符号必须由库定义的两个原因。首先,检测错误,例如代码中的符号名称是否有拼写错误。您希望链接器能够通知您该符号将永远不可用。其次(可能更重要),因为链接器和动态加载器的两级命名空间特性。对于动态库或框架提供的符号,链接器不仅记录符号名称,还记录解析它的库或框架。在加载时,符号与两者匹配。这允许两个动态库提供相同的符号,而不会有冲突或不正确绑定(bind)的风险。

如果您想针对 10.8 SDK 进行构建并仍然有条件地使用 AXIsProcessTrustedWithOptions(),您将需要使用动态加载。您将使用 dlopen() 打开/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices,然后使用 dlsym() 获取函数指针。检查指针是否不是 NULL,将其转换为正确的类型,然后您可以调用它指向的函数。

static bool IsSupported (void)
{
static Boolean (*pAXIsProcessTrustedWithOptions)(CFDictionaryRef options);

static dispatch_once_t once;
dispatch_once(&once, ^{
void* handle = dlopen("/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices", 0);
if (handle)
pAXIsProcessTrustedWithOptions = dlsym(handle, "AXIsProcessTrustedWithOptions");
};

return pAXIsProcessTrustedWithOptions ?
pAXIsProcessTrustedWithOptions (NULL):
AXAPIEnabled() || AXIsProcessTrusted();
}

关于c++ - weak_import 生成链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26076826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com