简体   繁体   English

在C中实现include预处理程序

[英]implementation of include preprocessor in c

I want to write a C program for implementing the include functionality of the preprocessor. 我想编写一个C程序来实现预处理器的include功能。

Example: 例:

In header.h I have this code: 在header.h中,我有以下代码:

char *test (void);

And in program.c: 并在program.c中:

int x;
#include "header.h"
int
main (void)
{
    puts (test ());
}

The input is program.c . 输入是program.c

The output must be : 输出必须是:

int x;
char *test (void);
int
main (void)
{
    puts (test ());
}

How can I do this? 我怎样才能做到这一点?

You'd need to read the input file line by line. 您需要逐行阅读输入文件。 Check to see if the line starts with #include (with optional leading whitespace). 检查行是否以#include开头(带有可选的前导空格)。 If not, print the line you've read. 如果没有,请打印您已阅读的行。 If so, open the specified file instead, and run this same algorithm on it (to handle secondary #includes). 如果是这样,请改为打开指定的文件,然后在其上运行相同的算法(以处理辅助#includes)。

you can run gcc -E "your source files", and then filter the line included "#",the left is your wanted, and the macros is replaced by its real forms. 您可以运行gcc -E“您的源文件”,然后过滤包含“#”的行,左边是您想要的,宏将替换为其实际形式。

for example: 例如:

gcc -E hello.c|sed '/# .,$/d' > a.c

ac is your wanted file. ac是您想要的文件。

when use gcc 使用gcc时
gcc -E -P program.c gcc -E -P program.c

or 要么
cpp -P program.c cpp -P程序

when use Visual c 使用Visual c时
cl /EP program.c cl / EP程式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM