helloworld.c编译成ELF文件过程讲解(预处理,编译,汇编,链接)

Code:

liam@ubuntu:~/practice$ cat HelloWorld.c   
#include <stdio.h>
int main()
{
        //print hello world
        printf("hello world!\n");
        return 0;
}

一、预编译后:

liam@ubuntu:~/practice$ mips-linux-gnu-gcc -E HelloWorld.c -o hello

展开宏,展开头文件,去掉注释,处理条件编译指令,添加行号和文件名标示...

二、编译:

mips-linux-gnu-gcc -S HelloWorld.c -o hello.S

liam@ubuntu:~/practice$ cat hello.S
.file 1 "HelloWorld.c"
.section .mdebug.abi32
.previous
.gnu_attribute 4, 1
.abicalls
.option pic0
.rdata
.align 2
$LC0:
.ascii "hello world!\000"
.text
.align 2
.globl main
.set nomips16
.set nomicromips
.ent main
.type main, @function
main:
.frame $fp,32,$31 # vars= 0, regs= 2/0, args= 16, gp= 8
.mask 0xc0000000,-4
.fmask 0x00000000,0
.set noreorder
.set nomacro

addiu $sp,$sp,-32
sw $31,28($sp)
sw $fp,24($sp)
move $fp,$sp
lui $2,%hi($LC0)
addiu $4,$2,%lo($LC0)
jal puts
nop

move $2,$0
move $sp,$fp
lw $31,28($sp)
lw $fp,24($sp)
addiu $sp,$sp,32
j $31
nop

.set macro
.set reorder
.end main
.size main, .-main
.ident "GCC: (Sourcery G++ Lite 4.4-303) 4.4.1"

三、汇编:

liam@ubuntu:~/practice$ mips-linux-gnu-as hello.S -o hello.o
liam@ubuntu:~/practice$ file hello.o
hello.o: ELF 32-bit MSB relocatable, MIPS, MIPS-I version 1 (SYSV), not stripped

注意此时的hello.o还无法执行。

上面的指令合起来等于:liam@ubuntu:~/practice$ mips-linux-gnu-gcc -c HelloWorld.c -o hello.o


四、链接:

得到了hello.o后要得到可执行程序,还需要最后一个链接步骤。

mips-linux-gnu-ld hello.o -o hello.out -L xxxx xxx.o 后面还要链接一大堆的东西。

可用命令:liam@ubuntu:~/practice$ mips-linux-gnu-gcc HelloWorld.c  -v -o hello 看到打印的最后位置就是链接的命令。

 

最后得到的hello就是可执行的ELF文件:

liam@ubuntu:~/practice$ file hello
hello: ELF 32-bit MSB executable, MIPS, MIPS32 rel2 version 1, dynamically linked (uses shared libs), for GNU/Linux 2.6.12, not stripped

 

posted @ 2015-04-30 23:01  JustRelax  阅读(1548)  评论(0)    收藏  举报