简体   繁体   中英

implementation of include preprocessor in c

I want to write a C program for implementing the include functionality of the preprocessor.

Example:

In header.h I have this code:

char *test (void);

And in program.c:

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

The input is 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). 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).

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.

for example:

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

ac is your wanted file.

when use gcc
gcc -E -P program.c

or
cpp -P program.c

when use Visual c
cl /EP program.c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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