是否可以从C访问汇编中定义的变量? [英] Is it possible to access variables defined in assembly from C?

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

问题描述

我可以读取或写入在我的C文件中的程序集文件中定义的变量吗?我自己想不通.例如,C文件如下所示:

Can I read from or write to a variable defined in my assembly file in my C file? I couldn't figure it out on my own. For example the C file looks as follows:

int num = 33;

并生成以下汇编代码:

    .file   "test.c"
    .globl  _num
    .data
    .align 4
_num:
    .long   33

当我开始学习汇编时,我经常听到速度是我必须选择汇编,减小文件大小和所有其他内容的原因...

As i started to learn assembly i heard often the speed is the reason why i have to pick assembly and lower file size and all that stuff...

我在Windows 7上使用mingw(32位)gnu程序集

I am using mingw(32 bit) gnu assembly on windows 7

推荐答案

是的,Linker合并了所有.o文件(从.s文件构建),并创建了一个目标文件.因此,所有c文件将首先成为程序集文件.

Yes, Linker combines all the .o files (built from .s files) and makes a single object file. So all your c files will first become assembly files.

每个程序集文件都有一个导入列表和一个导出列表.导出列表包含所有具有.global.globl指令的变量.导入列表包含c文件中所有以extern开头的变量. (但是,与NASM不同,GAS不需要声明导入.文件中未定义的所有符号都假定为外部符号.但是生成的.o.obj对象文件将具有符号导入列表,它们使用,并且需要在其他地方定义.)

Each assembly file will have an import list, and an export list. Export list contains all the variables that have a .global or .globl directive. Import list contains all the variables that start with a extern in the c file. (GAS, unlike NASM, doesn't require declaring imports, though. All symbols that aren't defined in the file are assumed to be external. But the resulting .o or .obj object files will have import lists of symbols they use, and require to be defined somewhere else.)

因此,如果您的程序集文件包含以下内容:

So if your assembly file contains this:

    .globl  _num        # _num is a global symbol, when it is defined
    .data               # switch to read-write data section
    .align 4
_num:                   # declare the label 
    .long  33           # 4 bytes of initialized storage after the label

要使用num,您需要做的就是创建一个这样的extern变量

All you need to do in order to use num, is to create a extern variable like this

extern int num;  // declare the num variable as extern in your C code   

然后您就可以阅读或修改它.

and then you'll be able to read it or modify it.

许多平台(Windows,OS X)在符号名称前添加了下划线,因此C变量num的asm名称为_num. Linux/ELF不会执行此操作,因此asm名称也将为num.

Many platforms (Windows, OS X) add a leading underscore to symbol names, so the C variable num has an asm name of _num. Linux/ELF doesn't do this, so the asm name would also be num.

这篇关于是否可以从C访问汇编中定义的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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