Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 952
Jackson Avatar asked Dec 19 '10 04:12

Jackson


Video Answer


1 Answers

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.

like image 130
Matt Wilding Avatar answered Oct 19 '22 00:10

Matt Wilding