c++ - 使用GCC对C文件进行部分预处理(不删除 “define”指令)

标签 c++ gcc c-preprocessor

如果我传递-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/

相关文章:

c++ - 如何在 clang 3.4 中使用 make_unique?

c++ - 父类可以调用其子类版本的函数

c++ - FPU 命令 FLDL 将 ST0 中的 double 转换为 long double

c++ - glibc 函数的 GCC、-flto、-fno-builtin 和自定义函数实现

c - 可变宏和尾随逗号

c - 如何使用 header 将多个 c 文件链接在一起?

c++ - 被信号 11(SIGSEGV) 和/或 6(SIGABRT) 杀死

c++ - 在 C++ 中编写移动构造函数时是否必须编写复制构造函数?

C++11 正则表达式匹配

c++ - 为什么链接顺序会影响使用宏的测试的测试结果?