Alex Rivera | Logout

How to use typed constants with "unused variable" warnings?

Asked 2013-02-18T23:34:57.370
9

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.

Edit
Report

1 Answer

13

Clang will allow you to push and pop warning flags onto and from a "diagnostic" stack: "Controlling diagnostics via pragmas". You can wrap certain pieces of code like this:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"

static NSString *kErrorCannotDivideByZero = @"Error: Cannot divide by zero";

#pragma clang diagnostic pop

to tell Clang that you know these aren't used, and that's okay in this particular instance.

Incidentally, you may not want to define these variables in a file that's being imported to many different places -- that's a good way to cause linker errors about variable redefinition (although this would only happen if the variable were globally linked -- declared/defined without static). The usual pattern for constants like this is to put an extern declaration in the header, and define the variable in another file. See Referencing a static NSString * const from another class for details.

As dreamlax has pointed out, you're actually getting these warnings because each file which imports your header is getting its own copy of the static variable; when I suggested the #pragma technique above, I was misunderstanding what you were asking for.

answered 2013-02-18T23:40:07.883

Your Answer