C 预处理器的输出文件

Output file of the C Preprocessor

理论题: C 预处理器的语言格式到底是什么。我知道它的作用,它的用途,当它被调用时但我找不到任何地方如果它的输出是:a)汇编代码,b)C源代码(据说它看起来像它)或c)机器语言(我不认为这是它,而是一个猜测)。

当预处理被集成到 C 编译器中时,它在编译器中的输出可能是预处理器标记和 white-space 序列的形式,它们都是有效地排列成组的字符序列,表示在内部以编译器设计者选择的任何方式。 (例如,输入文本 int main(void) 的标记将是 int main(void).)

当预处理器输出写入文件时,它是根据需要使用白色-space 字符分隔标记的文本。此输出是无需进一步预处理即可编译的源代码;您可以像处理普通 C 源代码一样将其提供给 C 编译器。但是,它可能包含其他非标准文本以支持编译器功能,例如 # 行包含有关原始源文件名和行号的信息。

Theoretical question: What exactly is the language-format of the C Preprocessor. I know what it does, what it is used for, when it gets called but i cannot find ANYWHERE if its output is: a) assembly code, b)C source code(it is said that it can look like it) or c)machine language (I don't think this is it, but a guess).

好吧,它是一个与 C 编译器相关的 Pre-processor...任何地方搜索的地方可能有点多:必须为每个地方提供文档编译器在编译器选项中,所以它必须是搜索的一个地方

预处理器不是编译器,预处理器只知道文本。它接收文本、输出文本、拦截以 # 开头的内容并执行其操作。就像 nroff 一样。

所以预处理器输出没有语言格式:它只是文本

在 Windows

上使用 gcc 10.2 的示例

搜索 gcc preprocessor output option 会在第一页获得此内容

无论如何引用 gcc docs

If you use the -E option, nothing is done except preprocessing. Some of these options make sense only together with -E because they cause the preprocessor output to be unsuitable for actual compilation.

文件pp1.h

// pp1.h
    int x = 300;
// end of pp1.h    

文件pp2.h

// pp2.h
    return 
// end of pp2.h    

文件pp.c

#include "pp1.h"

int main(void)
{
                #include "pp2.h" 
    x;
}
// end of pp.c

gcc -E pp.c

的输出
# 1 "pp.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "pp.c"
# 1 "pp1.h" 1

    int x = 300;
# 2 "pp.c" 2

int main(void)
{
# 1 "pp2.h" 1

    return
# 6 "pp.c" 2
    x;
}

由于 -E 选项,代码未编译,但它肯定是有效的 C,因为这是我们一直在做的:使用一些 #define、一些 #include 并编译我们的代码。
我们可以再次将其通过管道传输到 gcc 并像往常一样使用

生成程序
    gcc -E pp.c | gcc -o pp.exe -xc -

和运行程序照常:

C:\src>pp

C:\src>echo %ERRORLEVEL%
300

对通用文本使用预处理器

当然,这是一个糟糕的使用,但只是作为案例的 5 分钟说明,这里 t1.txt 是一个城市列表:

t1.txt

#include "t1.h"

Microsoft Corporate Offices Addresses(where found)

Austin
Costa Mesa
Houston 
Nashville
Memphis
Mountain View

t1.h

header 有一个城市和地址列表

#define    Nashville \
    Nashville: Corporate Sales Office \
    8 City Boulevard, Suite 403 \
    Nashville, TN, USA \
    37209

#define     Memphis \
    Memphis: Corporate Sales Office \
    6465 N. Quail Hollow Road, Suite 200 \
    Memphis, TN, USA \
    38120

#define     Houston \
    Houston: Corporate Sales Office \
    750 Town and Country Boulevard, St. 1000 \
    Houston, TX, USA \
    77024
// end of t1.h

预处理器输出

这个命令

gcc -E -x c t1.txt | grep -v "^#"

在 gcc 10.2 下显示


Microsoft Corporate Offices Addresses(where found)

Austin
Costa Mesa
Houston: Corporate Sales Office 750 Town and Country Boulevard, St. 1000 Houston, TX, USA 77024
Nashville: Corporate Sales Office 8 City Boulevard, Suite 403 Nashville, TN, USA 37209
Memphis: Corporate Sales Office 6465 N. Quail Hollow Road, Suite 200 Memphis, TN, USA 38120
Mountain View

输出明显的结果:在列表中找到办公室地址后将其附加到城市。

只是一个玩具。预处理器不懂编程语言。