运行C语言时,中间那些姿势你了解吗?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/g8433373/article/details/87892937

1分钟了解下C语言运行时做了什么

简介

  • 我们运行一个c语言程序的时候会经历几个过程,分别是:预编译->编译->汇编->连接,下面通过实践简单了解下。

运行过程

测试代码

# include<stdio.h>

// 文件名 hello.c
int main(){
    printf("hello\n");
    return 0;
}

预处理

$ gcc -E hello.c -o hello.i
  • 查看下hello.i的内容,发现非常多,这一步其实就是预编译过程,个人理解就是去找那些依赖的库

编译

  • 这一步其实就是将预处理之后的内容转化成汇编语言
$ gcc -S hello.i -o hello.s
  • 我们看下hello.s文件
	.section	__TEXT,__text,regular,pure_instructions
	.build_version macos, 10, 14
	.globl	_main                   ## -- Begin function main
	.p2align	4, 0x90
_main:                                  ## @main
	.cfi_startproc
## %bb.0:
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset %rbp, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register %rbp
	subq	$16, %rsp
	leaq	L_.str(%rip), %rdi
	movl	$0, -4(%rbp)
	movb	$0, %al
	callq	_printf
	xorl	%ecx, %ecx
	movl	%eax, -8(%rbp)          ## 4-byte Spill
	movl	%ecx, %eax
	addq	$16, %rsp
	popq	%rbp
	retq
	.cfi_endproc
                                        ## -- End function
	.section	__TEXT,__cstring,cstring_literals
L_.str:                                 ## @.str
	.asciz	"hello\n"


.subsections_via_symbols

汇编

  • 这一步就是生成目标文件
$ gcc -c hello.s -o hello.o

连接

  • 将上面生成的目标文件和一些动态,静态库连接起来,最后就成了最后的可执行文件hello
$ gcc hello.o -o hello

运行

  • 最后运行看下结果
xxx.macPro$ ./hello
hello

快捷方法

  • 其实真正运行的时候只需要运行一条命令就行了,但是要知道过程中经历了什么才更有意思吧
$ gcc hello.c -o hello

参考

[1] gcc命令详解

猜你喜欢

转载自blog.csdn.net/g8433373/article/details/87892937