#define指令问题

时间:2009-07-17 17:22:54

标签: c objective-c

我有以下代码:

#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

我的问题是什么?为什么这段代码不能编译?

感谢。

4 个答案:

答案 0 :(得分: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'语句是非常邪恶的,并且会让每个人都感到困惑。不要这样做。

答案 1 :(得分:3)

问题是您不能在宏中包含预处理程序指令。 您可能希望这样做:

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

还要确保“return”行执行您认为的操作(此处,它退出调用checkLiteMessage的函数,而不仅仅是宏(宏不能“退出”)。

答案 2 :(得分: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      

答案 3 :(得分:0)

预处理器只是一次通过。所以序列#ifdef正在进入编译器,导致错误。使其成为一种功能。