Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
227 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...