Objective-C 中的全局变量 - extern 和 .m 文件顶部声明的区别

发布于 2024-10-08 06:51:13 字数 221 浏览 0 评论 0原文

我知道你可以使用“extern”在 Objective-C 中定义一个全局变量,但我刚刚意识到我在第一个方法之前在 .m 文件顶部声明的变量也意外地是全局的(这导致了一些问题)问题)。我将它们移入头文件的 @interface 部分,我认为这正确地将它们声明为仅存在于类中,这解决了我的一些问题,但我仍然有点困惑。

将变量声明为 extern 并将其放在 .m 文件的顶部有什么区别?或者这些会导致同样的结果吗?

I know you can define a global variable in Objective-C by using "extern", but I just realized that the variables I had declared at the top of my .m file before my first method were also accidentally global (and that was causing some problems). I moved them into the @interface part of my header file, which I think correctly declares them as only existing within the class, which has solved some of my problems, but I am still a bit confused.

What is the difference in declaring a variable as extern and putting it at the top of a .m file? Or do those result in the same thing?

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

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

发布评论

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

评论(1

风轻花落早 2024-10-15 06:51:13

extern 是一种明确声明的方式,为了可读性和编译时执行,您只是在此处声明此变量,并且实际上期望它在其他地方定义。如果您还尝试定义 extern 变量,编译器会告诉您方法的错误。这对于全局变量来说非常有用,可以防止名称冲突和多重定义,这两者都会导致链接器错误。然而,extern 关键字本身并不使该变量成为全局变量。

使变量成为全局变量的是其在文件中声明的位置。如果您要在类的头文件中的 @interface 之外声明一个变量,那么您将声明一个在类的所有实例以及 #imports 标头的任何人之间共享且可见的变量。如果您要(并且显然确实)在类的 .m 文件中的 @implementation 之外声明了一个变量,那么您还将声明一个在类的所有实例之间共享的变量,但对任何人来说都是不可见的。 #导入你的标题。

因此,使用变量声明的位置来确定范围。您只需在一处定义这些全局变量。对于您声明的所有其他位置,请在声明前添加 extern 前缀,以使代码可读、您的意图清晰,并确保您不会尝试再次定义它。

extern is a way of explicitly stating, for readability and compile-time enforcement, that you are just declaring this variable here, and actually expect it to be defined elsewhere. If you were to also try to define the extern variable the compiler will tell you the error of your ways. This is useful for global variables to prevent name collision and multiple definitions, both of which will get you linker errors. The extern keyword itself, however, does not make the variable global.

What does make the variable global is the position of its declaration in the file. If you were to declare a variable outside the @interface in a class' header file, you would have declared a variable that is shared across and visible to all instances of your class, as well as anyone who #imports the header. If you were to (and apparently did) declare a variable outside of the @implementation in your class' .m file, you would have also have declared a variable that is shared between all instances of your class, but is not visible to anyone who #imports you header.

So, use the position of variable declarations to determine scope. You will only define these global variables in one place. For all other places that you declare them, prefix the declaration with extern to make the code readable, your intentions clear, and to make sure you don't also try and define it again.

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