gpt4 book ai didi

c - 宏模板和扩展

转载 作者:行者123 更新时间:2023-11-30 15:33:45 24 4
gpt4 key购买 nike

Consider the following program.

Practice.c

#include <stdio.h>
#define P(x,y,z) (x+y+z)

main()
{
int x,y,z,i,j,k;

printf("\n Number I = ");
scanf("%d",&i);
printf("\n Number II = ");
scanf("%d",&j);
printf("\nNumber III = ");
scanf("%d",&k);

printf("\n Result = %d\n",P(i,j,k));
}

现在如果我运行 gcc -E Practice.c比输出将是

# 2 "Practice.c" 2


main()
{
int x,y,z,i,j,k;

printf("\n Number I = ");
scanf("%d",&i);
printf("\n Number II = ");
scanf("%d",&j);
printf("\nNumber III = ");
scanf("%d",&k);

printf("\n Result = %d\n",(i+j+k));
}

In here, the macro P(i,j,k) is replaced by (i+j+k) and it is clearly visible on the command screen.

我的问题是, #include <stdio.h> 到底发生了什么?在这里?

它是否也会被 stdio 的文件替换? ,与 #define P(x,y,z) (x+y+z) 相同或者它只是链接 stdio 内容的一种方式到main() .

而且,# 2 "Practice.c" 2 是什么?在使用 gcc -E Practice.c 后的输出中?

最佳答案

在预处理期间,#include 指令实际上被包含文件的内容替换。此外,这个包含文件本身是经过预处理的,因此如果它包含任何其他包含指令,则会包含另一个文件等。

通常,预处理器和编译器是两个不同的程序,预处理的输出通过管道发送到编译器。编译器本身不会打开和读取源文件。

在这种情况下,很明显必须有一种机制,预处理器可以告诉编译器代码的来源。这对于错误消息是必要的。如果存在语法错误,预处理器不会检测到它,编译器会发现它,并且编译器需要显示错误所在的确切行和源文件。然而,当仅从管道读取一个流时,如果没有附加形式就不可能获取此信息。这就是为什么像

这样的行
 # 2 "Practice.c" 2

出现。它是有关源代码实际来源的信息。在这种情况下,预处理器通知该行后面的代码来自文件“Practice.c”,下一行是该源代码的第二行。然后,编译器可以增加下一个行序列的行号,直到下一个这样的指令(通常称为并用作 #line 指令)。

关于c - 宏模板和扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23588791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com