Using C++ and GCC, can I declare an extern variable that uses a specific address in memory? Something like
int key __attribute__((__at(0x9000)));
AFAIK this specific option only works on embedded systems. If there is such an option for use on the x86 platform, how can I use it?
Easy option:
Define
int * const key = (int *)0x9000;
and refer to *key
elsewhere (or use a reference).
Pointerless option:
All externs have specific addresses! These addresses may not be known until link time, but they must get resolved eventually. If you declare extern int key;
then you must supply an address for the symbol key
at link time. This can be done using a linker script (see Using ld) or at the linker command line, using the --defsym
option.
If running gcc, you could use the -Xlinker
flag to pass the option on to the linker. In your example,
gcc -o outfile -Xlinker --defsym -Xlinker key=0x9000 sourcefile.c
The following program, thus compiled, outputs 0x9000
.
#include <stdio.h>
extern int key;
int main(void) {
printf("%p\n", &key);
return 0;
}
If you have a collection of variables you want to be in some region of memory, a more appropriate method might be to use output sections as suggested by Nikolai, perhaps in conjunction with a custom ld
script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With