Global variables in Objective-C - difference in extern and top of .m file declaration

后端 未结 1 1345
無奈伤痛
無奈伤痛 2021-02-05 23:44

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

相关标签:
1条回答
  • 2021-02-06 00:26

    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.

    0 讨论(0)
提交回复
热议问题