从Asm访问用C定义的全局变量 [英] Accessing global variable defined in C from Asm

查看:538
本文介绍了从Asm访问用C定义的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C文件,其中包含全局变量foo.如何从另一个Assemby程序访问 foo .
我正在使用i586-elf-as(GNU汇编程序)和i586-elf-gcc(gnu编译器)进行构建.

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.

推荐答案

您可以只使用符号名称; as将所有未定义的符号视为外部符号.

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

检查编译器输出(gcc -S)和/或文档,以了解C变量名称是否以前置_开头. (在许多非ELF平台上,int myglobal变为asm _myglobal,但在Linux/ELF上仍为myglobal.)

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.)

当然,如果使用C ++编译器(除了extern "C"变量之外),则会发生C ++名称更改.

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

如果要显式声明,则有一个.extern指令,GAS会忽略该指令(与其他Unix汇编程序兼容). GAS手册中的文档

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


例如在x86-64,lea myglobal(%rip), %rsimov $myglobal, %esi上,以AT& T语法将地址保存到寄存器中.


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

mov myglobal(%rip), %eax从中加载.或者mov global, %eax使用32位绝对地址以32位模式从其加载,因为RIP相对寻址仅在64位模式下可用.

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.

这篇关于从Asm访问用C定义的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆