Question

I have a C file which contain a global variable foo. How I can access foo from another assemby program.
I am using i586-elf-as (GNU assembler) and i586-elf-gcc (gnu compiler) for building.

Was it helpful?

Solution

You can just use the symbol name; as treats all undefined symbols as external.

Check compiler output (gcc -S) and/or documentation to find out if C variable names get a leading _ prepended or not. (int myglobal becomes asm _myglobal on many non-ELF platforms, but still myglobal on Linux/ELF.)

And of course C++ name mangling happens if you use a C++ compiler, except for extern "C" variables.


If you want to declare it explicitly, there's a .extern directive which GAS ignores (for compat with some other Unix assemblers). Documentation in the GAS manual

.extern foo       # ignored, no extra checking is done because of this

For example on x86-64, lea myglobal(%rip), %rsi or mov $myglobal, %esi to get the address into a register in AT&T syntax.

Or mov myglobal(%rip), %eax to load from it. Or mov global, %eax to load from it in 32-bit mode, using a 32-bit absolute address because RIP-relative addressing is only available in 64-bit mode.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top