带有静态指针的 Objective-C 类别:如何避免未定义符号错误?

发布于 2024-10-02 01:14:09 字数 847 浏览 2 评论 0原文

我有一个来自外部库的类,我想用一个类别来扩展它。但是,此类使用多个静态变量,例如:

static SomeClass* someClass;

我扩展的类别方法必须调用此类,如

-(void) categoryMethod
{
   [someClass someMethod];
}

如果我这样做,编译器会抱怨:

'someClass' was not declared in this scope

所以我想我可能需要将静态 SomeClass 声明为extern:

extern SomeClass* someClass;

但是,这会导致以下链接器错误:

"_someClass", referenced from:
_someClass$non_lazy_ptr in UsingSomeClass.o
(maybe you meant: _someClass$non_lazy_ptr)
Symbol(s) not found

我认为我错过了一些简单而愚蠢的东西。我可以很好地使用静态库。我猜测静态变量是我想要扩展的类的本地变量,有什么方法可以告诉链接器这些是我要使用的静态变量吗?

或者是否无法扩展使用静态变量的 Objective-C 类(分别是我的类别需要使用这些静态变量的地方)?

PS:由于我链接的是包含我想要扩展的类的静态库,所以我最初确实遇到了需要使用其他链接器标志 -ObjC 和 -all_load 解决的问题。但我已经过去了,这不是问题,我可以在该静态库中为其他类编写类别就好了。

I have a class from an external library that I want to extend with a category. However, this class uses several static variables, such as:

static SomeClass* someClass;

The category method I'm extending must make a call to this class, as in

-(void) categoryMethod
{
   [someClass someMethod];
}

If I do that the compiler will complain:

'someClass' was not declared in this scope

So I figured I probably need to declare the static SomeClass as extern:

extern SomeClass* someClass;

However, that leads to the following linker error:

"_someClass", referenced from:
_someClass$non_lazy_ptr in UsingSomeClass.o
(maybe you meant: _someClass$non_lazy_ptr)
Symbol(s) not found

I think I'm missing something simple and stupid. I can use the static library just fine. I'm guessing that the static variables are local to the class I want to extend, is there any way to tell the linker that those are the static variables I'm meaning to use?

Or is it just not possible to extend an Objective-C class that uses static variables (respectively where my category needs to use these static variables)?

PS: since I'm linking the static library which contains the class I want to extend, I did originally face the problem that needs to be solved with the Other Linker Flags -ObjC and -all_load. But I've been past that, it's not the problem, I can write categories for other classes in that static library just fine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不再见 2024-10-09 01:14:09

C 中的静态变量(因此在 Objective-C 中)不能在定义它的编译单元之外引用。它是一个内部符号,不能用“外部”来引用。

所以,不,您的类别方法无法访问该静态变量。

另请注意,“静态”一词的这种用法与静态库与动态库无关。

A static variable in C (and, therefore, in Objective-C) cannot be referenced outside the compilation unit that defines it. It's an internal symbol that you can't refer to with an "extern".

So, no, there isn't any way your category method can access that static variable.

Note also that this usage of the word "static" has nothing to do with static vs. dynamic libraries.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文