c - 是否有可能在 C 中实现无限编译时间(即没有模板)?

标签 c compilation

所以,标题。众所周知,可以编写 C++ 程序,这将需要无限的时间来编译(理论上)。但是可以用纯 C 编写这样的程序吗?或者有没有办法用一个小程序将编译时间减慢到至少几分钟?

最佳答案

这是您要求的示例,其中的宏呈指数增长。

#define FOO  i++  // Substitute any statement here for i++
#define FOO1 FOO ; FOO
#define FOO2 FOO1 ; FOO1
#define FOO3 FOO2 ; FOO2
#define FOO4 FOO3 ; FOO3
#define FOO5 FOO4 ; FOO4
#define FOO6 FOO5 ; FOO5
// Keep going however much you want
...
#define FOO40 FOO39 ; FOO39

volatile int i;

int main(void)
{
    FOO40;  // This expands to 2^40 statements.
}

我使用 FOO18 进行计时测试,看看会发生什么。我分别测试了预处理器时间和编译时间:

(Preprocessor phase)
time gcc -E foo.c -o foo.i
1.7 seconds

(Compilation phase)
time gcc foo.i -o foo
21 seconds

出于好奇,我一直在尝试越来越大的值(value)。不幸的是,编译器有时会耗尽内存(预处理器没问题)。我收到此错误:

cc1: out of memory allocating 16842751 bytes after a total of 403505152 bytes

FOO16-O2 中,我能够在不耗尽内存的情况下获得 2:23 的编译时间。因此,如果您想获得更长的编译时间,请首先找出可以放入单个函数中而不会耗尽内存的许多语句(对我来说是FOO16)。然后做几个函数,像这样:

int main(void)
{
    FOO16;
}

void bar1(void)
{
    FOO16;
}

void bar2(void)
{
    FOO16;
}

// etc...

关于c - 是否有可能在 C 中实现无限编译时间(即没有模板)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29334637/

相关文章:

c - 通用动态数组未正确更新属性

c - 将字符串解析为参数时出现额外的空字符串

c - 如何使用 fread 从文件中读取特定数据?

compilation - 编译为 LLVM 字节码,然后编译为机器码对速度等有什么影响?

c++ - 如何计算或查看编译时生成的指令数?

c - C 中的 PlaySound 发出蜂鸣声但不播放 wav 文件

java - 如何在 linux 上为 JNI 应用程序编译动态库?

java - 这有什么问题吗?我找不到符号

scala - SBT 错误的编译顺序

c - Linux 内核定义无处不在