【问题标题】:implementation of include preprocessor in c在c中实现包含预处理器
【发布时间】:2012-06-14 00:49:40
【问题描述】:

我想编写一个 C 程序来实现预处理器的include 功能。

例子:

在 header.h 我有这个代码:

char *test (void);

在program.c中:

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

输入是program.c

输出必须是:

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

我该怎么做?

【问题讨论】:

  • 你在哪里定义了 test() ?
  • 在 header.h 我定义了 test()。
  • 实现一个最小的预处理器应该相当容易。如果您好奇,可以查看 Sourceforge 上的 mcppGnu cpplib 之类的内容

标签: c preprocessor


【解决方案1】:

您需要逐行读取输入文件。检查该行是否以#include 开头(带有可选的前导空格)。如果没有,请打印您已阅读的行。如果是这样,请打开指定的文件,并在其上运行相同的算法(以处理辅助#includes)。

【讨论】:

  • @AComputert 打开一个文件,逐行读取,跟踪 cmets 和字符串,这样您就不会尝试处理语句 printf("#include <stdio.h>\n"); 或注释 /* #include <notfoundhere.h> */。或者将其全部读入内存并扫描;或使用mmap() 使其在内存中可用。或者...
【解决方案2】:

你可以运行gcc -E "你的源文件",然后过滤包含"#"的行,左边是你想要的,宏被替换成它的真实形式。

例如:

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

a.c 是你想要的文件。

【讨论】:

    【解决方案3】:

    当使用 gcc
    gcc -E -P program.c


    cpp -P program.c

    当使用 Visual c
    cl /EP program.c

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      相关资源
      最近更新 更多