background image

C 语言宏中"#"和"##"

 

的用法

在查看 linux 内核源码的过程中,遇到了许多宏,这里面有许多都涉及到"#"和"##",因此,
在网上搜索了一些资料,整理如下:

 

一、一般用法
我们使用#把宏参数变为一个字符串,用##把两个宏参数贴合在一起. 
用法: 
#include<cstdio> 
#include<climits> 
using namespace std; 

#define STR(s)     #s 
#define CONS(a,b)  int(a##e##b) 

int main() 

    printf(STR(vck));           // 输出字符串"vck" 
    printf("%d\n", CONS(2,3));  // 2e3 输出:2000 
    return 0; 

 

二、当宏参数是另一个宏的时候
需要注意的是凡宏定义里有用'#'或'##'的地方宏参数是不会再展开. 

1, 非'#'和'##'

 

的情况

#define TOW      (2) 
#define MUL(a,b) (a*b) 

printf("%d*%d=%d\n", TOW, TOW, MUL(TOW,TOW)); 

 

这行的宏会被展开为:
printf("%d*%d=%d\n", (2), (2), ((2)*(2))); 
MUL 里的参数 TOW 会被展开为(2). 

2, 当有'#'或'##'

 

的时候

#define A          (2) 
#define STR(s)     #s 
#define CONS(a,b)  int(a##e##b) 

printf("int max: %s\n",  STR(INT_MAX));    // INT_MAX #include<climits> 

 

这行会被展开为:
printf("int max: %s\n", "INT_MAX"); 

printf("%s\n", CONS(A, A));               // compile error