所以,标题。众所周知,可以编写 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/