How do global variables contribute to the size of the executable?

Do global variables have an executable file size? If so, how? Does the size only increase the size of the data section or the size of the text section?

If I have a global variable and initialization as shown below:

char g_glbarr[1024] = {"jhgdasdghaKJSDGksgJKASDGHKDGAJKsdghkajdgaDGKAjdghaJKSDGHAjksdghJKDG"};

Now, does 1024 add the size of the initialization string to the text section in the data section?

If instead of allocating space for this array statically, if I malloc it and then do memcpy, will only the data section be reduced in size or the size of the text section will be reduced?

+3
source share
4 answers

, . . , char (, printf("<1024 char array goes here");), (AFAIK /Borland?/ ). ( V++ #pragma data_seg(<segment name>)).

/, .

+5

, ( ):

  • , , . , ( ).
  • , "" . ( ELF-based, , Windows ?) "rodata" , , .
  • "" , .
  • ( ) , "bss", .
  • "bss" - , , const -qualified.
+3

, , . , , , - .

, "" ? !

+2

, . g_glbarr char . , g_glbarr . , .

@Jay, . () : , , , . - . , - :

// warning: I haven't compiled this and wouldn't normally
// do it quite this way so I'm not positive this is
// completely grammatical C
struct X {int a; char * b; } x = { 1, "Hello" } ; 

1becomes “immediate” data, "Hello"is allocated in read-only data somewhere, and the compiler simply generates what allocates a portion of the read-write data, which looks something like

x:
x.a:   WORD    1
x.b    WORD    @STR42

where STR42is the symbolic name for placing the string "Hello"in memory. Then, when everything is connected to each other, it @STR42is replaced by the actual virtual address of the line in memory.

+1
source

Source: https://habr.com/ru/post/1778462/


All Articles