如何使用条件预处理器排除以下代码

时间:2013-09-10 11:11:47

标签: c++ macros c-preprocessor

例如

typedef union
{
    struct
    { 
        unsigned fb_num                :  8 __attribute__ ((packed));
        unsigned stream_id             : 12 __attribute__ ((packed));
        unsigned lossless              :  1 __attribute__ ((packed));
        unsigned proto_idx             :  6 __attribute__ ((packed));
        unsigned da_logport            : 13 __attribute__ ((packed));
        unsigned sa_spare_dx           : 10 __attribute__ ((packed));
        unsigned da_spare_idx          : 10 __attribute__ ((packed));
        unsigned mcast_index           : 12 __attribute__ ((packed));/* ISH_B*/
        unsigned mesh_idx              :  8 __attribute__ ((packed));
        unsigned in_mirror             :  4 __attribute__ ((packed));
        unsigned vlan_idx              : 12 __attribute__ ((packed));
        unsigned dis_stp               :  1 __attribute__ ((packed));
        unsigned trkbal_idx            :  5 __attribute__ ((packed));
...

我想要排除此代码部分:__attribute__ ((packed)),以便编译器将其读取为:

typedef union
{
    struct
    { 
        unsigned fb_num                :  8 ;
        unsigned stream_id             : 12 ;
        unsigned lossless              :  1 ;
        unsigned proto_idx             :  6 ;
        unsigned da_logport            : 13 ;
        unsigned sa_spare_dx           : 10 ;
        unsigned da_spare_idx          : 10 ;
        unsigned mcast_index           : 12 ;/* ISH_B*/
        unsigned mesh_idx              :  8 ;
        unsigned in_mirror             :  4 ;
        unsigned vlan_idx              : 12 ;
        unsigned dis_stp               :  1 ;
        unsigned trkbal_idx            :  5 ;
...

现在应该编译的MACRO是MCAST_SIMULATION: 即如果定义了MCAST_SIMULATION,则不包括所提到的代码部分。 我怎么能做到这一点?

3 个答案:

答案 0 :(得分:1)

您将__attribute__()定义为无。

像这样:

#ifdef MCAST_SIMULATION
# define __attribute__(x)
#endif

答案 1 :(得分:1)

您可以为此引入自己的宏。类似的东西:

#ifndef MCAST_SIMULATION
#define ATTRIB_PACKED __attribute__((packed))
#else
#define ATTRIB_PACKED
#endif

用法:

unsigned fb_num :  8 ATTRIB_PACKED ;

答案 2 :(得分:1)

将文字__attribute__ ((packed))替换为宏(例如 PACKED,并有条件地定义:

#ifndef MCAST_SIMULATION
#define PACKED __attribute__ ((packed))
#else
#define PACKED
#endif