Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why setting a value of global array has impact on executable file?

Tags:

c++

g++

c++20

When I set my array to {1,1}, size of the executable file increase from 10 KiB to 7 MiB. But when I set it to {}, the size doesn't change.

long long fib[1000001] = {1,1}; // 7 MiB
long long fib[1000001] = {}; // 10 KiB

I use C++20 and g++ 8.1.0.

It only happens with global variables and it doesn't matter what type of memory it uses.

like image 771
Matian Avatar asked Nov 18 '25 17:11

Matian


1 Answers

If a global variable is initialized to zero, the executable does not have to contain actual storage for it. It merely needs to tell the OS's executable loader that "I need X storage of bytes for global data", and the loader will provide that. That memory will be zeroed out.

However, if a global variable is initialized to something non-zero, even partially, then its data has to come from somewhere. The simplest solution is to generate the bytes of data at compile-time and shove them into the executable. At runtime, references to the global variable point into the loaded executable's storage.

While this is platform/OS specific, it's generally how most executables and compilers work

like image 166
Nicol Bolas Avatar answered Nov 21 '25 05:11

Nicol Bolas