C宏可以更改宏关键字

psy*_*ave 3 c macros

宏允许在C中轻松地为关键字设置别名,但也可以用它来更改宏关键字,因此代替:

#include <stdlib.h>

#define se if
Run Code Online (Sandbox Code Playgroud)

一个人可以写

#inkludu <stdlib.h>

#difinu se if
Run Code Online (Sandbox Code Playgroud)

换句话说,预处理指令可以别名,最好是代码本身,例如使用编译器参数,例如-Dgcc.

如下所示的简单测试将失败:

#define difinu define
#difinu valoro 2

int main() {
    int a?o = valoro;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

出现以下错误:

 % clang makro.c -o makro
makro.c:2:2: error: invalid preprocessing directive
#difinu valoro 2
 ^
makro.c:5:16: error: use of undeclared identifier 'valoro'
    int a?o = valoro;
              ^
2 errors generated.
Run Code Online (Sandbox Code Playgroud)

Bas*_*tch 6

不.宏不会改变预处理器指令的处理方式(但当然可以根据条件指令改变#if).特别是,以下是错误的

///WRONG CODE
#define inc include
/// the following directive is not recognized as an include
#inc <stdio.h>
Run Code Online (Sandbox Code Playgroud)

顺便说一下,有

#define se if
Run Code Online (Sandbox Code Playgroud)

即使有可能,也是一个坏习惯.它使您的代码se (x>0) {printf("negative x=%d\n", x);}更难以阅读.

考虑使用其他预处理器m4GPP预处理源代码.这等于从其他东西生成您的C(或C++)代码.

我的感觉是元编程通常是一个好主意:你编写一些专门的程序,例如发出C或C++代码(并且你改进你的构建过程,例如你的Makefile,相应的).但是你可能会设计一个真正的C或C++代码生成器(可以处理和处理某种类型的AST).像ANTLRbison这样的解析器生成器(错误地称为编译器编译器)就是一个很好的例子.而且Qt有.moc

又见这个那个回答相关问题.

在尝试使用自己的代码生成器(或特定于域的语言实现)之前,不要忘记阅读几本教科书(特别是与编译器相关).