Accessing global variable defined in C from Asm

有些话、适合烂在心里 提交于 2019-12-20 02:27:15

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/17365638/accessing-global-variable-defined-in-c-from-asm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!