Search code examples
c++binaryobjdump

Why are global and static objects stored in the section of bss


I'm studying the sections of a binary file. I used the c++ code below:

// test.cpp
struct Test {
    int i;
    Test(int ii) : i(ii) {}
    Test() {}
};

Test t0{5};
Test t1 = Test(5);
Test t2;
static Test t3;
static Test t4{5};

int i = 1;
int j;
static int k;
static int l = 1;


int main() {
    return 0;
}

I compiled this code with the command g++ test.cpp and get a binary file named a.out.

Then, I used the command objdump to extract the sections of bss and data.

The output of objdump -dj .data a.out:

a.out:     file format elf64-x86-64


Disassembly of section .data:

0000000000201000 <__data_start>:
        ...

0000000000201008 <__dso_handle>:
  201008:       08 10 20 00 00 00 00 00                             .. .....

0000000000201010 <i>:
  201010:       01 00 00 00                                         ....

0000000000201014 <_ZL1l>:
  201014:       01 00 00 00                                         ....

The output of objdump -dj .bss a.out:

a.out:     file format elf64-x86-64


Disassembly of section .bss:

0000000000201018 <__bss_start>:
  201018:       00 00                   add    %al,(%rax)
        ...

000000000020101c <t0>:
  20101c:       00 00 00 00                                         ....

0000000000201020 <t1>:
  201020:       00 00 00 00                                         ....

0000000000201024 <t2>:
  201024:       00 00 00 00                                         ....

0000000000201028 <j>:
  201028:       00 00 00 00                                         ....

000000000020102c <_ZStL8__ioinit>:
  20102c:       00 00 00 00                                         ....

0000000000201030 <_ZL2t3>:
  201030:       00 00 00 00                                         ....

0000000000201034 <_ZL2t4>:
  201034:       00 00 00 00                                         ....

0000000000201038 <_ZL1k>:
        ...

So, the variables i and l are stored in the section .data because they were initialized. The variables j and k are in the section .bss because they were not initialized. I can understand that.

But why are all of the objects of Test are in the section .bss even if those initialized objects? I thought t0, t1 and t4 should be stored in the section .data but obviously I'm wrong.


Solution

  • .data is only used for variables that are initialized with literal data.

    The Test objects are initialized using the constructor method. So the memory is allocated in bss, then during startup the constructor is called to fill in the contents.