wiki:FromCtoRunningProgram

From C to Running Program

  • 相关指令
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ gedit main.c 
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ gcc -E -o main.cpp main.c 
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ ls
main.c  main.cpp
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ gedit main.cpp 
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ gcc -x cpp-output -S -o main.s main.cpp 
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ ls
main.c  main.cpp  main.s
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ gedit main.s
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ gcc -x assembler -c main.s -o main.o
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ ls
main.c  main.cpp  main.o  main.s
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ gedit main.o
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ gcc -o main main.o
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ ls
main  main.c  main.cpp  main.o  main.s
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ ./main
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ ls
main  main.c  main.cpp  main.o  main.s
ubuntu@ubuntu:/mnt/hgfs/linux/gcc$ 
  • C代码
int g(int x)
{
	return x+3;
}

int f(int x)
{
	return g(x);
}

int main(void)
{
	return f(8)+1;
}
  • 对应的汇编代码
	.file	"main.c"
	.text
.globl g
	.type	g, @function
g:
	pushl	%ebp # subl $4, %esp & movl %ebp,(%esp)
	movl	%esp, %ebp
	movl	8(%ebp), %eax
	addl	$3, %eax
	popl	%ebp # movl (%esp),%ebp & addl $4, %esp
	ret # popl %eip
	.size	g, .-g
.globl f
	.type	f, @function
f:
	pushl	%ebp
	movl	%esp, %ebp
	subl	$4, %esp
	movl	8(%ebp), %eax
	movl	%eax, (%esp)
	call	g # pushl %eip & movl g, %eip
	leave
	ret
	.size	f, .-f
.globl main
	.type	main, @function
main:
	pushl	%ebp
	movl	%esp, %ebp
	subl	$4, %esp
	movl	$8, (%esp)
	call	f
	addl	$1, %eax
	leave
	ret
	.size	main, .-main
	.ident	"GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
	.section	.note.GNU-stack,"",@progbits

Last modified 6 years ago Last modified on 02/12/12 11:59:38