在 运行 内存不足之前我可以声明多少个 const 变量?

How many const variables can I declare before running out of memory?

我正在编写包含大量常量变量(主要是整数和枚举)的代码,我想知道我可以声明的变量数量是否有上限?我的想法是,这些 const 变量分配在堆栈上,这意味着我可以声明大约 1MB/4bytes = 250000 个变量(足够了),假设堆栈的大小为 1MB。我说得对吗?

我的意思的一个简单例子:

Test.cpp:

const unsigned int VECTOR_ID = 4;
const unsigned int MATRIX_ID = 3;

int main()
{
  std::cout << VECTOR_ID << " : " << MATRIX_ID << std::endl;
  return 0;
}

请注意,编译时已知的常量可能不对应任何对象;当您在启用优化的情况下进行编译时,常量将作为 立即值直接编译到机器指令中。 Here 是一个简单的示例。这意味着对常量变量本身的数量没有限制。这也意味着根本不使用的常量可能会完全消失。 (并且 如果 它们以任何非平凡的方式使用,代码的大小将超过数据的大小。)

即使你的常量确实变成了对象,例如因为它们的地址已被占用,所以它们将是 "compiled into your program" 并且成为可执行文件的一部分。

程序的大小及其段的大小受可执行文件格式、系统资源以及可能受构建工具的限制。 Intel page 似乎表明即使在 64 位架构上,静态数据(全局常量可能结束)在 Windows 下也被限制为 2 GB(这仍然比您的用例大三个数量级) :

Note that the limit on static and stack data is the same in both 32-bit and 64-bit variants. This is due to the format of the Windows Portable Executable (PE) file type, which is used to describe EXEs and DLLs as laid out by the linker. It has 32-bit fields for image section offsets and lengths and was not extended for 64-bit variants of Windows. As on 32-bit Windows, static data and stack share the same first 2GB of address space.

快速搜索似乎表明现代 Linux 中不存在此限制。