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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With