分步骤完成
gcc -E hello.c -o hello.i
1.预处理 展开头文件 比如 /usr/include/stdio.h
gcc -S hello.i -o hello.s
2.编译
gcc -c hello.s -o hello.o
3.汇编
gcc hello.o -o hello
4.链接
一步到位
gcc hello.c -o hello
运行程序: ./hello
gcc hello.c 默认生成的是a.out
案例
[root@iZ5bg01fils2m1fw0td6qgZ aa]# make clean
rm *.o main a.out -rf
[root@iZ5bg01fils2m1fw0td6qgZ aa]# ll
total 20
-rw-r--r-- 1 root root 120 Jul 20 16:59 head.h
-rw-r--r-- 1 root root 201 Jul 20 16:58 main.c
-rw-r--r-- 1 root root 199 Jul 20 17:07 Makefile
-rw-r--r-- 1 root root 64 Jul 20 17:07 sub.c
-rw-r--r-- 1 root root 64 Jul 20 16:59 sum.c
[root@iZ5bg01fils2m1fw0td6qgZ aa]#
[root@iZ5bg01fils2m1fw0td6qgZ aa]# cat head.h
#ifndef _HEAD_H_
#define _HEAD_H_
#include <stdio.h>
int sum(int a, int b);
int sub(int a, int b);
#endif // HEAD_H
[root@iZ5bg01fils2m1fw0td6qgZ aa]# cat main.c
#include <stdio.h>
#include "head.h"
int main()
{
int x = 1000;
int y = 900;
printf("%d + %d = %d\n", x, y, sum(x, y));
printf("%d - %d = %d\n", x, y, sub(x, y));
return 0;
}
[root@iZ5bg01fils2m1fw0td6qgZ aa]# cat Makefile
main:main.o sub.o sum.o
gcc main.o sub.o sum.o -o main
main.o:main.c
gcc -c main.c -o main.o
sub.o:sub.c
gcc -c sub.c -o sub.o
sum.o:sum.c
gcc -c sum.c -o sum.o
clean:
rm *.o main a.out -rf
[root@iZ5bg01fils2m1fw0td6qgZ aa]# cat sub.c
#include "head.h"
int sub(int a, int b)
{
return a - b;
}
[root@iZ5bg01fils2m1fw0td6qgZ aa]# cat sum.c
#include "head.h"
int sum(int a, int b)
{
return a + b;
}
[root@iZ5bg01fils2m1fw0td6qgZ aa]#
[root@iZ5bg01fils2m1fw0td6qgZ aa]# make
gcc -c main.c -o main.o
gcc -c sub.c -o sub.o
gcc -c sum.c -o sum.o
gcc main.o sub.o sum.o -o main
[root@iZ5bg01fils2m1fw0td6qgZ aa]# echo $?
0
[root@iZ5bg01fils2m1fw0td6qgZ aa]# file main
main: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, BuildID[sha1]=71baabf447141a0350625b2ee73e856a171ea235, not stripped
[root@iZ5bg01fils2m1fw0td6qgZ aa]#
[root@iZ5bg01fils2m1fw0td6qgZ aa]# ./main
1000 + 900 = 1900
1000 - 900 = 100
[root@iZ5bg01fils2m1fw0td6qgZ aa]# ll
total 44
-rw-r--r-- 1 root root 120 Jul 20 16:59 head.h
-rwxr-xr-x 1 root root 8472 Jul 20 17:09 main
-rw-r--r-- 1 root root 201 Jul 20 16:58 main.c
-rw-r--r-- 1 root root 1752 Jul 20 17:09 main.o
-rw-r--r-- 1 root root 199 Jul 20 17:07 Makefile
-rw-r--r-- 1 root root 64 Jul 20 17:07 sub.c
-rw-r--r-- 1 root root 1240 Jul 20 17:09 sub.o
-rw-r--r-- 1 root root 64 Jul 20 16:59 sum.c
-rw-r--r-- 1 root root 1240 Jul 20 17:09 sum.o
[root@iZ5bg01fils2m1fw0td6qgZ aa]#
Makefile
- 最精简版
- 预定义变量
- 自定义变量语法
- 未使用变量