2009-07-17 83 views
0

我有下面的代码:#define指令问题

#define checkLiteMessage \ 
{ \ 
    #ifdef LITE_VERSION \ 
    if (alertView.tag == 100) \ 
    { \ 
     if (buttonIndex == 1) \ 
     [ [UIApplication sharedApplication] openURL: buyAppLink]; \ 
     [alertView release]; \ 
     return; \ 
    } \ 
    #endif \ 
} \ 

我想要做的是有下面的代码被列入每次我打电话checkLiteMessage时间:

#ifdef LITE_VERSION 
    if (alertView.tag == 100) 
    { 
     if (buttonIndex == 1) 
     [ [UIApplication sharedApplication] openURL: buyAppLink]; 
     [alertView release]; 
     return; 
    } 
    #endif 

什么我的问题?为什么不编译这个代码?

谢谢。

回答

8

你已经用连续线指定了宏,这是正确的。但是,这意味着#ifdef语句不在行的开头,所以预处理器不会这样做。

您不能在宏内嵌入#ifdef。你可以扭转:

#ifdef LITE_VERSION 
#define checkLiteMessage do { \ 
    if (alertView.tag == 100) \ 
    { \ 
     if (buttonIndex == 1) \ 
     [ [UIApplication sharedApplication] openURL: buyAppLink];  \ 
     [alertView release]; \ 
     return; \ 
    } \ 
} while(0) 
#else 
#define checkLiteMessage do { ; } while (0) 
#endif 

我要补充的是把一个“return”语句在宏内部是非常邪恶的,将是混乱给大家。不要这样做。

+0

+1,肯定好办法解决:) – 2009-07-17 17:31:40

+0

速度打字课程应该是强制性的。做得好。 – 2009-07-17 17:35:42

1

的反斜杠换行符组合等同于没有字母都这样

#define x y \ 
    z 

相当于

#define x y z 

而且,根据该标准,在宏体预处理器指令不展开或解释,并将#ifdef传递给编译器,而不是有条件地将代码放在两者之间。

您可以检查此行为创建文件a.c与内容

#define x y \ 
    z 

#define v \ 
     #ifdef E 

x 

v 

,并命令gcc -E a.c预处理它。

在你的情况,你需要做的是

#ifdef LITE_VERSION 
#define checkLiteMessage \ 
{ \ 
    if (alertView.tag == 100) \ 
    { \ 
     if (buttonIndex == 1) \ 
     [ [UIApplication sharedApplication] openURL: buyAppLink];  \ 
     [alertView release]; \ 
     return; \ 
    } \ 
} 
#else 
#define checkLiteMessage 
#endif  
0

预处理器只有一个通。所以序列#ifdef正在进入您的编译器,导致错误。让它成为一个功能。

+0

不,它不是一次通过的,预处理器指令不会扩展,但任何宏都会扩展,直到在特定扩展期间第二次达到名称。 – 2009-07-17 20:18:13

3

问题是,您不能在宏中包含预处理器指令。 你可能想这样做,而不是:

#ifdef LITE_VERSION 
#define checkLiteMessage \ 
{ \ 
    if (alertView.tag == 100) \ 
    { \ 
     if (buttonIndex == 1) \ 
     [ [UIApplication sharedApplication] openURL: buyAppLink];  \ 
     [alertView release]; \ 
     return; \ 
    } \ 
} 
#else 
#define checkLiteMessage 
#endif 

还要确保“返回”行做什么,你认为它(在这里,它退出函数调用checkLiteMessage,而不仅仅是宏(宏不能“exited”)