Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1176266
  • 博文数量: 115
  • 博客积分: 950
  • 博客等级: 准尉
  • 技术积分: 1734
  • 用 户 组: 普通用户
  • 注册时间: 2011-12-08 20:46
文章分类

全部博文(115)

文章存档

2015年(5)

2014年(28)

2013年(42)

2012年(40)

分类: LINUX

2012-05-18 14:21:03

Refer:Using #error and #warning Compiler Directives


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.

阅读(2117) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~