Macros 聚集 in c++
在 c++ 中,一个 Macro 就是一段代码的聚合。使用这个 macro 名称就代表着对应的代码段。
有两种常见的 macro:object 形式,function 形式。可以定义任意有效的字符作为 macro 名称,甚至是 c 关键词。
object 形式
object 形式的 macro 就是简单的使用一个 identifier 代替代码片段。使用 #define 定义一个 macro:
#define TESTINT 1024
void main() {
int a = TESTINT;
cout << a << endl;
}
//output:
//1024也可以定义一个片段:
#define NUMBERS 1, 2, 3
void main() {
int x[] = { NUMBERS };
//int x[] = { 1, 2, 3 };这两句效果相同
}也可以多层定义:
#define NUMBER1 1
#define NUMBER2 NUMBER1以上示例中 NUMBER2 等于 NUMBER1。
function 形式
可以定义 function 形式的 macro,需要在定义中 macro 名称后加上圆括号()。例如:
#define lang_init() c_init()定义后就可以使用 lang_init() 来调用 c_init() 了,类似于 alias。
object 类型的 macro 可以和 function 类型的 macro 同名,区别就是有没有圆括号:
#define test 100
#define test() func()
void main() {
int a = test;
test();
}以上就是对 macro 的简单介绍。
参考链接:
https://gcc.gnu.org/onlinedocs/cpp/Macros.html
标签:无