C语言和汇编语言的关系

在写驱动程序或者优化程序的时候,我门可能会使用到汇编语言,为了理解汇编语言,我们先看看下面这个简单的例子:

#this is in a file first.s
.global main
main:
    movl $20, %eax
    movl $10, $ebx
    ret

$20, %eax 意思是,将20拷贝到寄存器eax 中。

使用GNU C 的-S 选项,我们可以生成汇编代码,举个例子:

int main(){
    int x = 10;
    int y = 15;
    return 0;
}


我们使用-S选项来编译一下

它生成的汇编代码文件simple.s长这个样子:

	.file	"simpole.c"
	.text
	.globl	main
	.type	main, @function
main:
.LFB0:
	.cfi_startproc
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset 6, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register 6
	movl	$10, -4(%rbp)
	movl	$15, -8(%rbp)
	movl	$0, %eax
	popq	%rbp
	.cfi_def_cfa 7, 8
	ret
	.cfi_endproc


举这个例子的目的是为了让大家在一定程度上了解汇编语言,我们可以看到x, 和y的初始化过程,还有,大量用到了esp(stack 指针), ebp(base 指针)。每条指令后面的l 表明我们的操作符号作用于32位的操作数上面。寄存器用%表示。比如:

movl $10, -4(%ebp)

意思是将10 移动到ebp-4这个位置。


我们来看另外一个将C语言转换成汇编语言的例子:

#include <stdio.h>
int main()
{
    printf("hello world\n");
    return 0;
}

汇编代码:

	.file	"hello.c"
	.section	.rodata
.LC0:
	.string	"hello world"
	.text
	.globl	main
	.type	main, @function
main:
.LFB0:
	.cfi_startproc
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset 6, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register 6
	movl	$.LC0, %edi
	call	puts
	movl	$0, %eax
	popq	%rbp
	.cfi_def_cfa 7, 8
	ret
	.cfi_endproc
.LFE0:
	.size	main, .-main
	.ident	"GCC: (GNU) 4.8.2 20140120 (Red Hat 4.8.2-16)"
	.section	.note.GNU-stack,"",@progbits



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值