初始化和可执行文件体积——解释神秘CE:输出超限
概要
本文将介绍不同初始化方式对编译器行为的影响,从而解释出现“Nothing is compiled: OUTPUT exceeds”的原因,并提出避免方法。
引入
对比如下两段代码,分别在洛谷ide和笔者的电脑上编译:
Code
#include <iostream>
constexpr int kSize = 5e6;
int test_arr[kSize] = {0};
int main()
{
// 确保不被优化掉。
std::cin >> test_arr[0];
std::cout << test_arr[0];
}#include <iostream>
constexpr int kSize = 5e6;
int test_arr[kSize] = {1};
int main()
{
// 确保不被优化掉。
std::cin >> test_arr[0];
std::cout << test_arr[0];
}在洛谷上,第二份代码报错并输出“Nothing is compiled: OUTPUT exceeds”,而在笔者的电脑上编译得到的可执行文件大小分别为 222KB 和 19753KB,并且第二份代码的编译时间明显增加。
无独有偶,以下代码也能触发相同的错误。
More Code
第 5 行的 改为 后行为正常。
#include <iostream>
constexpr int kSize = 5e6;
struct test {
int a_ = 1;
} test_arr[kSize];
int main()
{
// 确保不被优化掉。
std::cin >> test_arr[0].a_;
std::cout << test_arr[0].a_;
}第 5 行的 改为 后行为正常。
#include <iostream>
constexpr int kSize = 5e6;
struct test {
int arr_[kSize] = {1};
} test_str;
int main()
{
// 确保不被优化掉。
std::cin >> test_str.arr_[0];
std::cout << test_str.arr_[0];
}使用 C++20 标准编译则不正常,更低标准正常。
#include <iostream>
#include <vector>
constexpr int kSize = 5e6;
struct test {
std::vector<int> arr_[kSize];
int a_ = 1;
} test_str;
int main()
{
// 确保不被优化掉。
std::cin >> test_str.a_;
std::cout << test_str.a_;
}而如果我们将变量定义为局部变量(即在 main 函数中定义),以上所有代码均表现正常(除非编译环境的栈空间不够大),出于篇幅原因,不再展示代码。
概念介绍
在我们分析造成可执行文件体积暴涨的原因之前,首先介绍一些概念。
- 编译期:
- 运行期:
- 作用域:
- 生命周期:
分析原因
利用 Compiler Explorer 可以很方便的查看代码编译得到的汇编语言。将以上代码
解决方法
许可证
鉴于洛谷并没有对文章的许可证加以限制,本文在 CC BY-SA 4.0 协议下发布。 要浏览协议内容,请访问https://creativecommons.org/licenses/by-sa/4.0/。
以下说明不能替代完整协议,冲突之处以原文为准:
总体来说,你可以自由分享和修改本文内容,只要你在发布时使用相同(或兼容)的协议,并且给出适当的署名。