A global variable is always initialized to zero

I wrote the OS using this tutorial. I am in the part where the bootloader is completed and C is used for programming (and then linked together ...). But this is as a note, I believe that the problem I have is related to gcc.

I am creating an i386-elf cross compiler for the OS. And everything works fine, I can execute my code, everything works. Except that all global variables are initialized to zero , although I provided a default value .

 int test_var = 1234; // yes, void main() is correct (the boot-loader will call this) void main() {} 

If I debug this code using GDB, I get: ( gcc-7.1.0, target: i328-elf )

 (gdb) b main Breakpoint 1 at 0x1554: file src/kernel/main.c, line 11. (gdb) c Continuing. Breakpoint 1, main () at src/kernel/main.c:11 11 void main() { (gdb) p test_var $1 = 0 

If I run the same code on my local computer ( gcc-6.3.0, target: x86_64 ), it prints 1234 .

My question is: I incorrectly defined gcc, is this a bug in my OS, is this a known issue? I could not find anything about this.

All my source code: link I use the following commands to compile my stuff:

 # ... i386-elf-gcc -g -ffreestanding -Iinclude/ -c src/kernel/main.c -o out/kernel/main.o # ... i386-elf-ld -e 0x1000 -Ttext 0x1000 -o out/kernel.elf out/kernel_entry.o out/kernel/main.o # some other stuff ... i386-elf-objcopy -O binary out/kernel.elf out/kernel.bin cat out/boot.bin out/kernel.bin > out/os.bin qemu-system-i386 -drive "format=raw,file=out/os.bin" 

EDIT: like @EugeneSh. suggested some logic here to make sure it is not removed:

 #include <cpu/types.h> #include <cpu/isr.h> #include <kernel/print.h> #include <driver/vga.h> int test_var = 1234; void main() { vga_text_init(); switch (test_var) { case 1234: print("That correct"); break; case 0: print("It zero"); break; // I don't have a method like atoi() in place, I would use // GDB to get the value default: print("It something else"); } } 

Sorry, it prints It zero

+7
c gcc cross-compiling
source share
1 answer

The compiler never clears uninitialized global variables to zero, its logic is built-in inside the loader, so when you allocate memory for a data segment, then it also contains a bss section. Thus, you should check the offset, alignment and size of the bss section with the data segment and memset () to "0".

When you write your OS, it is possible that all library procedures are not available, therefore it is better to use the memset () function using the assembly.

+1
source share

All Articles