函数式宏定义的几种情况

//main.c 

#define MAX(a,b) ((a)>(b)?(a):(b))          //a、b必须用括号扩起来。因为可能是个表达式,展开后运算优先级会变化
k = MAX(i&2,j&2);

#define STR(s) # s                          // #是个运算符,只能用于函数式宏定义,用于创建字符串。 s中有多个连续的空间或tab被替换为一个空格
str = STR(lang      xian          wen);

#define CONCAT(a,b) a##b                    // ##也是个运算符,可用于变量式宏定义,把ab两个符号连在一起, 如 android中 virtual ~I##INTERFACE();   

concat = CONCAT(langx,ianwen);

#define HASH_HASH # ## #                    // 把两个# 连载一起。
hash_hash = HASH_HASH ;

用cpp工具查看展开结果
langu@langu:~/linuxk/link/define_macro/function_macro$ cpp main.c 
# 1 "main.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "main.c"

k = ((i&2)>(j&2)?(i&2):(j&2));

str = "lang xian wen";

concat = langxianwen;

hash_hash = ## ;

定义一个宏函数的时候,常定义在do { ... } while(0)里面.如:

#define MAX(a,b) \

        do { 

           ((a)>(b)?(a):(b)) 

} while(0)


看android源码中 的例子一次定义类多个函数:
#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \
    const android::String16 I##INTERFACE::descriptor(NAME);             \
    const android::String16&                                            \
            I##INTERFACE::getInterfaceDescriptor() const {              \
        return I##INTERFACE::descriptor;                                \
    }                                                                   \
    android::sp<I##INTERFACE> I##INTERFACE::asInterface(                \
            const android::sp<android::IBinder>& obj)                   \
    {                                                                   \
        android::sp<I##INTERFACE> intr;                                 \
        if (obj != NULL) {                                              \
            intr = static_cast<I##INTERFACE*>(                          \
                obj->queryLocalInterface(                               \
                        I##INTERFACE::descriptor).get());               \
            if (intr == NULL) {                                         \
                intr = new Bp##INTERFACE(obj);                          \
            }                                                           \
        }                                                               \
        return intr;                                                    \
    }                                                                   \
    I##INTERFACE::I##INTERFACE() { }                                    \
    I##INTERFACE::~I##INTERFACE() { } 



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值