如果我传递-E
或-save-temps
命令行参数,则GCC可以输出经过完全预处理的C++源文件。
我的问题是,我能以某种方式获取经过部分预处理的C++源文件,其中
a)消除了不满足#if,#ifdef和#ifndef条件的代码片段,
b)#include指令已解析(包括头文件),等等
但
c)无法解析普通的#define指令?
(这将是必要的,而且真的很有帮助,因为我希望获得尽可能紧凑和可读的输出。
解决#if指令会缩短源代码,但是解决#define指令会使源代码的可读性降低,并且更加冗余。)
我试图创建一个尽可能紧凑的示例,以演示我想要实现的目标:
输入文件样本:
// header1.h
#ifndef header1_h
#define header1_h
int function1(int val) {
return val + MYCONST;
}
#endif
// header2.h
#ifndef header2_h
#define header2_h
int function1(int val) {
return val + val + MYCONST;
}
#endif
// main.c
#define MYCONST 1234
#define SETTING1
#ifdef SETTING1
#include "header1.h"
#endif
#ifdef SETTING2
#include "header2.h"
#endif
int main(void) {
int retVal = function1(99);
}
预期产量:
// main.i (GCC preprocessing output)
#define MYCONST 1234 // I would like to see the definition of MYCONST here
#define SETTING1
#define header1_h
int function1(int val) {
return val + MYCONST; // I would like to see MYCONST here instead of the resolved value
}
int main(void) {
int retVal = function1(99);
}
最佳答案
gcc
有一个 -fdirectives only
选项,它可以完成您所需的操作:
-fdirectives-only
When preprocessing, handle directives, but do not expand macros.
The option’s behavior depends on the -E and -fpreprocessed options.
With -E, preprocessing is limited to the handling of directives such as #define, #ifdef, and #error. Other preprocessor operations, such as macro expansion and trigraph conversion are not performed. In addition, the -dD option is implicitly enabled.
With -fpreprocessed, predefinition of command line and most builtin macros is disabled. Macros such as
__LINE__
, which are contextually dependent, are handled normally. This enables compilation of files previously preprocessed with -E -fdirectives-only.With both -E and -fpreprocessed, the rules for -fpreprocessed take precedence. This enables full preprocessing of files previously preprocessed with -E -fdirectives-only.
在您的情况下,应将其称为
% gcc -fdirectives-only -E -o main.i main.c
但是您得到的定义(内部定义的),空行和#line
行比您想要的更多。
关于c++ - 使用GCC对C文件进行部分预处理(不删除 “define”指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58806610/