C code how to use variables defined in the linker script?

Reference article:

https://sourceware.org/ml/binutils/2007-07/msg00154.html

Author: Wei Dongshan, 2017-1-3 write to ask a hundred Forums

Original Source:

http://bbs.100ask.org/forum.php?mod=viewthread&tid=16231

In the link scripts, often you have this code:

SECTIONS
{
.....
. = ALIGN(4);
.rodata : { *(.rodata) }

. = ALIGN(4);
.data : { *(.data) }

. = ALIGN(4);
.got : { *(.got) }

. = ALIGN(4);
__bss_start = .;
.bss : { *(.bss) }
_end = .;
}

Wherein __bss_start, _end BSS segment represents the start, end address.

When we want to clear this space,
1. In assembly code can be directly referenced __bss_start, _end, such as:

ldr r0, =__bss_start
ldr r1, =_end

2. In the C code, we can not use them directly, do this:

void clean_bss(void)
{
extern int __bss_start, _end;
int *p = &__bss_start;
   
for (; p < &_end; p++)
        *p = 0;
}

You may be wondering: __ bss_start, _end not represent a value it? In C code Why use the address symbol &?

Reasons:
First, in the C code, a statement such as:

int foo = 1000;

Will lead to two things happen:

  1. In the code, leaving 4 bytes of space, to save values ​​1000
  2. In symbole talbe C language, i.e., the symbol table, there is a named foo items inside it there was a 4-byte address space.

We execute foo = 1, it will go to find the address of the corresponding foo symbol table, and then fill in the value of 1 corresponding to the address of the memory;

When we execute int * a = & foo, will direct the symbol table foo address, wrote a.

Second, in the linker script, it is assumed

__bss_start = 1000

__bss_start is not a variable, it's just a value, do not need to leave some space in memory to save it;

In the C language, there will be a symbol table entry named __bss_start, this project value (address value) is 1000;

Note that this memory 1000 does not actually exist.

three.
So: In the C language, go to the link using the values defined in the script, you should do this:

extern int __bss_start;
int val = &__bss_start;

Use the address value to get it & notation in the symbol table.
Note that this value is only linked value defined in the script, does not mean that the address of a variable.



1, learn more embedded dry goods please pay attention to micro-channel public number [Hundred Questions Science and Technology]
2, technical discussions please add personal micro letter: 13,266,630,429
3. Wei Dongshan is facing old student recruitment agents and distributors, commission of 20%, are interested please contact individuals micro letter.

Published 135 original articles · won praise 401 · views 260 000 +

Guess you like

Origin blog.csdn.net/thisway_diy/article/details/101016296