define命令是C语言中的一个宏定义命令,它用来将一个标识符定义为一个字符串,该标识符被称为宏名,被定义的字符串称为替换文本
 
有参宏定义  
在使用时调用带参宏调用的一般形式为:宏名(实参表);
1 2 3 4 5 6 7 8 #define  add(x, y) (x + y) int  main () {     cout  << "1 plus 1 is "  << add(1 , 1.5 ) << ".\n" ;          system("pause" );     return (0 ); } 
 
这个“函数”定义了加法,但是该“函数”没有类型检查,有点类似模板,但没有模板安全,可以看做一个简单的模板。
宏定义中的特殊操作符 define 中的特殊操作符有#,##和… and __VA_ARGS__
1)# 假如希望在字符串中包含宏参数,ANSI C允许这样作,在类函数宏的替换部分,#符号用作一个预处理运算符,它可以把语言符号转化程字符串。例如,如果x是一个宏参量,那么#x可以把参数名转化成相应的字符串。该过程称为字符串化。
1 2 3 4 5 6 7 8 9 10 11 #incldue <stdio.h>  #define  PSQR(x) printf("the square of"  #x "is %d.\n" ,(x)*(x)) int  main (void ) {     int  y =4 ;     PSQR(y);          PSQR(2 +4 );          return  0 ; } 
 
2)##
##运算符可以用于类函数宏的替换部分。另外,##还可以用于类对象宏的替换部分。这个运算符把两个语言符号组合成单个语言符号。
1 2 3 4 5 6 7 8 9 10 #include  <stdio.h>  #define  XNAME(n) x##n #define  PXN(n) printf("x" #n" = %d\n" ,x##n) int  main (void ) {     int  XNAME (1 ) =12 ;     PXN(1 );          return  0 ; } 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #define  YLLoadRequest(REQUEST_METHOD, REQUEST_ID)                                               \ {\ __weak typeof(self) weakSelf = self;\ REQUEST_ID = [[YLAPIProxy sharedInstance] load##REQUEST_METHOD##WithParams:finalAPIParams useJSON:self.isRequestUsingJSON host:self.host path:self.child.path apiVersion:self.child.apiVersion success:^(YLResponseModel *response) {\     __strong typeof(weakSelf) strongSelf = weakSelf;\     [strongSelf dataDidLoad:response];\ } fail:^(YLResponseError *error ) {\     __strong typeof(weakSelf) strongSelf = weakSelf;\     [strongSelf dataLoadFailed:error ];\ }];\ self.requestIdMap[@(REQUEST_ID)]= @(REQUEST_ID);\ }\ YLLoadRequest(GET, requestId); YLLoadRequest(POST, requestId); 
 
(3)可变参数宏 …和__VA_ARGS__
__VA_ARGS__ 是一个可变参数的宏,很少人知道这个宏,这个可变参数的宏是新的C99规范中新增的,目前似乎只有gcc支持(VC6.0的编译器不支持)。 实现思想就是宏定义中参数列表的最后一个参数为省略号(也就是三个点)。这样预定义宏__VA_ARGS__就可以被用在替换部分中,替换省略号所代表的字符串。
1 2 3 4 5 6 7 8 9 10 #define  PR(...) printf(__VA_ARGS__) int  main () {     int  wt=1 ,sp=2 ;     PR("hello\n" );          PR("weight = %d, shipping = %d" ,wt,sp);          return  0 ; } 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 #define  INIT(...) self = super.init; \ if  (!self) return nil; \__VA_ARGS__; \ if  (!_arr) return nil; \_lock = dispatch_semaphore_create(1); \ return self; #define  LOCK(...) dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER); \ __VA_ARGS__; \ dispatch_semaphore_signal(_lock); 
 
参考 c/c++中define用法详解及代码示例