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
", &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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…