Although not your everyday directives, #error and #warning definitely
have there place. Let’s take a short look at a few examples where you
might find these directives helpful.
#error
When the preprocessor runs into the #error directive, it will write
an error to the console and generate a compile time error. You can also
include a text string which is displayed as an error message.
For example, when writing a previous blog post about using JSON and the Flickr API , I needed a way to flag developers who downloaded the source code to
insert their own Flickr ID into the application code. I did this by
using the following code which generated a compile time error and
displayed a message to the console informing the user what was up.
#error : Change this value to your Flickr key NSString *const FlickrAPIKey = @"your-key-here";
Another time this can be helpful is when you need to verify that some
particular value has been defined for the application. As a simple
example, let’s say the our application needs to be flagged as either a
paid or free app – we could write something similar to the following as a
verification this step has been completed:
// Validate the application type has been set #ifdef PAID_APP // Do something #elif FREE_APP // Do something else #else #error : No App type defined #endif`
When I write the error message notice that I insert a “:” character
as it helps to break apart the error message. Also worth mentioning is
that the preprocessor will work through all the source code files before
the compiler stops, which is nice in that you can have more than one
#error message. The figure below shows error messages from two separate
source files:
As a final example, I’ve also used this as a personal marker in a
block of code so that I could recall where I was and what I was working
on when setting something aside. This is nice if you need to walk away
from a project for some time and want an unavoidable reminder of where
you left off.
#error : Check this code first
#warning
The directive #warning is similar however the preprocessor doesn’t
stop when it finds this directive, it simply displays the message to the
console and keeps on with the task at hand. One common use of #warning
is to display information regarding deprecated code:
#warning : This method is deprecated, use someNewMethod instead
Note:
You can optionally surround the #error and #warning messages in quotes.