I'm new to using the linker script and there is a concept I'm not sure that i really understand. I know that i can use the linker script to allocate sections in the memory at certain addresses, but that's during compilation time, so can that address be a variable location that is determined during run time? and if yes, can i know how to do so in C? i can't seem to find any option of inserting variables inside the linker script as it only see everything as symbols. Thanks in advance.
-
you should read the concept of `pointer` in C,It might help you. – krpra Mar 27 '18 at 18:03
-
It really depends on the linker and its implementation. If you want to put a variable in a special location, then either use pointers to point to that location, or put it in its own data-segment that you map to that address. – Some programmer dude Mar 27 '18 at 18:05
-
so can i determine that location during runtime? i don't want it to at a fixed location in the memory – Mostafa Mar 27 '18 at 18:09
-
4Now you need to edit your question to tell us about the *actual* problem you want to solve. *Why* do you want to "allocate a variable to a certain address during run time"? If you want to do anything at run-time, it can't be done with a linker script. – Some programmer dude Mar 27 '18 at 18:13
-
In C, learning the address of a section which have been located at runtime can be done with the `&` operator applied to any label in that section. The reverse operation, specifying the placement of a section, is OS-dependent; services like `mmap(2)` does that (among others uses.) – AntoineL Mar 27 '18 at 18:34
1 Answers
Why would you want to? If you need a specific address, it must be known a prori, so why not statically link it? You'd need to designate the space in the link map in any case, otherwise the linker will be free to allocate something else there - it is the only way you will know the location is available.
Of course you could reserve a range of addresses in the link map, and then arbitrarily access anywhere within that space at run time. That however is not really "allocating a variable" - variables either have statically linked addresses, are on the stack, or in a register. But you can create a pointer variable and set its address withing the reserved space.
However the normal reason for specifying a specific address is where such an address has some specific property such as an SFR or memory mapped I/O. Such addresses are generally fixed, so runtime determination not necessary.
If there is a circumstance where you have some device whose address is determined at run-time, which is possible but perhaps rare, then you need not involve the linker to address it; for example:
volatile uint32_t* devreg = getDeviceAddress() ;
*devreg = 0x01 ; // Write 1 to device register
devreg[0] = 0x02 ; // An alternative syntax
devreg[1] = 0x03 ; // Write to device's second register
uint32_t status = devreg[2] ; // Read devices 3rd register

- 88,407
- 13
- 85
- 165