Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

c++ - Extern variable at specific address

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...