How can I declare a variable at an absolute addres

2019-08-10 09:00发布

问题:

We are looking at how the linker works in one of my courses and one of the assignments is a little exercise involving the nm command. essentially we just want to match the type and the value printed by nm for each variable. for example:

char* B = NULL;

would give the address (irrelevant) then B B. I've done this successfully for all the labels we needed to except for A. I have read that this simply means the value is absolute and cannot be changed by the linker. I have experimented with many combinations involving volatile, const, static, define, and any thing else I could think to try, but I am presently out of ideas. I had read elsewhere that this could only be achieved by creating a linker script to do so, but that is not the case, as some of me peers have solved this with one line in C. Could any one come up with a way in C to output:

some address A A
...

Whem nm is called on it's object file?

回答1:

Defining absolute symbols in Standard C is a bit tricky. But you can use non-standard inline assembly:

$ cat x.c
asm (".globl A");
asm ("A = 0x42");
$ clang -c x.c
$ nm x.o
0000000000000042 A A