Accessing global variable defined in C from Asm

后端 未结 1 1435
广开言路
广开言路 2021-01-21 05:06

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-el

相关标签:
1条回答
  • 2021-01-21 05:29

    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.

    0 讨论(0)
提交回复
热议问题