I'm using Xcode 4.6 and I've got a header file which includes some constants I use throughout my code. I don't want to use preprocessor directives because I want them to be properly typed and such.
For example, I have this code in one of my .h files:
static NSString *kErrorCannotDivideByZero = @"Error: Cannot divide by zero";
and I use it in the corresponding .m file:
[self showToast:kErrorCannotDivideByZero];
I get the warning:
/path/to/my/headerFile.h:32:18: Unused variable 'kErrorCannotDivideByZero'
I know it's just a warning, but I've got about 50 of these warnings clogging up my compiler output.
Why am I getting this warning and how do I PROPERLY resolve it?
I'm not interested in simply suppressing all unused variable warnings, because I do want to get the legit ones.
Solution: If variable <variable_name> or function <function_name> is not used, it can be removed. If it is only used sometimes, you can use __attribute__((unused)) . This attribute suppresses these warnings.
No nothing is wrong the compiler just warns you that you declared a variable and you are not using it. It is just a warning not an error. While nothing is wrong, You must avoid declaring variables that you do not need because they just occupy memory and add to the overhead when they are not needed in the first place.
Make the declaration in your header extern
rather that static
. What you're doing is creating a variable for every translation unit that includes your header, and this is why Clang is warning you, because it is legitimately a defined variable that is not being used. The extern
keyword tells the compiler that the definition of the variable is found somewhere else (it might be in the same translation unit or it might be in another).
In your header, have:
// declare that the constant exists somewhere
extern NSString * const kErrorCannotDivideByZero;
And in one of your .m
files (typically the one that shares the same name as the header), put
// define the constant, i.e. this is where it exists
NSString * const kErrorCannotDivideByZero = @"Error: Cannot divide by zero";
Declaring variables extern
allows the compiler to ensure you are treating the variable correctly even if it doesn't know where it is defined (e.g. you can't use it as an NSArray
). The linker has the job of making sure you actually defined it somewhere.
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