I've seen 2 ways of creating global variables, what's the difference, and when do you use each?
//.h
extern NSString * const MyConstant;
//.m
NSString * const MyConstant = @"MyConstant";
and
//.h
extern NSString *MyConstant;
//.m
NSString *MyConstant = @"MyConstant";
In a const variable declaration, it specifies that the variable has external linkage. The extern must be applied to all declarations in all files. (Global const variables have internal linkage by default.) extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention.
Yes, you can use them together.
Master C and Embedded C Programming- Learn as you goThe “extern” keyword is used to declare and define the external variables. The keyword [ extern “C” ] is used to declare functions in C++ which is implemented and compiled in C language. It uses C libraries in C++ language.
extern void f(); declares that there is a function f taking no arguments and with no return value defined somewhere in the program; extern is redundant, but sometimes considered good style.
the former is ideal for constants because the string it points to cannot be changed:
//.h
extern NSString * const MyConstant;
//.m
NSString * const MyConstant = @"MyConstant";
...
MyConstant = @"Bad Stuff"; // << YAY! compiler error
and
//.h
extern NSString *MyConstant;
//.m
NSString *MyConstant = @"MyConstant";
...
MyConstant = @"Bad Stuff"; // << NO compiler error =\
in short, use const (the former) by default. the compiler will let you know if you try to change it down the road - then you can decide if it was a mistake on your behalf, or if the object it points to may change. it's a nice safeguard which saves a lot of bugs/headscratching.
the other variation is for a value:
extern int MyInteger; // << value may be changed anytime
extern const int MyInteger; // << a proper constant
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