【问题标题】:Can I make cpp not to output space line on #pragma?我可以让 cpp 不在#pragma 上输出空格行吗?
【发布时间】:2019-01-17 14:51:14
【问题描述】:

我正在用 #pragma push_macro#pragma pop_macro 在 C 预处理器中编写图灵机。我想让它在预处理完成后直接输出结果,而不是输出一个仍然需要运行才能得到结果的仅打印程序。

部分源码:

// main.c
int printf(char*, ...);
int main() {
    #define CODEFILE "command.c"
    #include "turing.h"
    #undef CODEFILE
}
// turing.h
#ifndef PARSE
#define PARSE(x) x
#pragma push_macro("PARSE")
#undef PARSE
#pragma pop_macro("PARSE")
#ifndef PARSE
#error push_macro/pop_macro not supported!
#else
#define GET03(x,y,z) x
#define GET13(x,y,z) y
#define GET23(x,y,z) z
#define GETN(n,l) PARSE(GET##n l)
#define COMMAND GETN(03, MOVE)
#define TNEXT GETN(13, MOVE)
#define FNEXT GETN(23, MOVE)
#define LEFT SPECIAL(1)
#define RIGHT SPECIAL(2)
#define NOP SPECIAL(3)
#define WARN SPECIAL(4)
#define HALT SPECIAL(5)
#define DEPTH 0
#pragma push_macro("DEPTH")
#undef DEPTH
#define DEPTH 1
#endif
#endif
#
#
#ifdef PARSE
#define STATUS 0
#define PTRL 0
#define PTR 0
#
#include "infloop.h"
#
#include "clrmemlp.h"
#
#pragma pop_macro("DEPTH")
#undef FINISHED
#undef STATUS
#undef PTRL
#undef PTR
#
#endif

运行cpp main.c 会得到:(有些行末尾包含空格)

# 1 "main.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "main.c"
int printf(char*, ...);
int main() {

# 1 "turing.h" 1





# 22 "turing.h"

# 34 "turing.h"
# 1 "infloop.h" 1

...

这里的行号很烦人。然后我在--help文档中看到:

  -P                          Do not generate #line directives

使用这个标志我可以得到

int printf(char*, ...);
int main() {








printf ("x = %d, ", 1);


...

但是仍然有大量的空行。好像来自#pragma,我也测试过:

1
#pragma push_macro("x")
2
#define x 3
3
#undef x
4
#include "nul"
5

结果是

1

2
3
4
5

所以我很确定空行来自#pragma。有什么办法可以避免吗?

【问题讨论】:

    标签: gcc c-preprocessor pragma


    【解决方案1】:

    是的,你说得对,#pragma 指令扩展为新行。好像gcc 没有选项来控制这种行为。

    一个最小的例子是:

    // turing.h
    #pragma push_macro("Test")
    
    // main.c
    int main() {
    #include "turing.h"
    }
    

    输出是:

    int main() {
    
    }
    

    还请看一下,编译器无法理解的 #pragma 指令会随着它的扩展而扩展。

    【讨论】:

    • 测试发现即使有一些空行也会被删除;然而#pragma#pragma 之间留下7+ 个空格,使它们无法删除
    • 我猜这取决于内容infloop.hclrmemlp.h
    • infloop.hclrmemlp.h的内容取决于什么?
    【解决方案2】:

    您总是可以通过过滤器提供输出:

    gcc -E -P main.c | grep '[^ ]'
    

    grep 选择所有包含非空格字符的行;换句话说,它会删除所有空行和仅包含空格的行。使用 GNU grep,您可以使用模式 \S,它也会忽略仅包含空格和制表符的行。

    【讨论】:

      猜你喜欢
      • 2013-02-04
      • 2022-10-01
      • 2012-07-16
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2021-05-07
      相关资源
      最近更新 更多