//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() { }
函数式宏定义的几种情况
最新推荐文章于 2022-03-18 10:41:18 发布