'Why is gcc placing my global data in the wrong address?

I am trying to compile an app for a custom OS I'm writing for the ARM Cortex M0+. The app is written in C. I have a global variable, int newInt = 4; defined at the very top of my code. The rest of the app just calls a print function to print out the value of that variable. However, it kept crashing. To check it, I instead printed out the address of the variable, newInt. It was well outside of the valid memory map of the chip, hence why it crashed.

My linker script is simple:

SECTIONS
{
    . = 0x20001580;
    .text : 
    {
        _text = .;
        *(.text)
        _etext = .;
    }
    .data : 
    {
        _data = .;
        KEEP(*(.data))
        _edata = .;
    }
    .bss :
    {
        _bss = .;
        *(.bss)
        _ebss = .;
    }
}

Now, the .text segment is placed correctly, starting at 0x20001580. However, the address of my global variable, which SHOULD be somewhere around that value (0x20001580 or so, plus the code size, which is around 40 bytes), is actually placed at 0x18060, which as far as I'm concerned is a totally random address. So, whenever I try to access newInt's value, the code tries to access an out of range memory address, and it fails.

Shouldn't newInt be placed in the .data segment? If so, why would the .data segment be at such an odd location, given my linker script?

gcc


Solution 1:[1]

This might be relevant to other people later:

The problem lay in my linking process. In order to make it work, I had to compile my app using the -c flag, to get the correct output file. THEN link against the output of gcc. I tried to do compilation and linking in one step and something went awry when that was done.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael Stachowsky