http://blog.youkuaiyun.com/ruglcc/article/details/7814546/
可以参考鸟哥的Linux私房菜 第668页
单一程序,打印 Hello World!
直接编译
编译程序源码,即源码
vim hello.c
内容如下:
#include <stdio.h>
void main()
{
printf("Hello World!");
}
开始编译与测试执行
gcc hello.c
查看当前目录下的文件:
ls
此时会产生如下两个文件
a.out hello.c
在默认状态下,如果直接以gcc编译源码,并且没有加上任何参数,这执行文件的文件名会被自动设置为a.out这个文件名。
./a.out #
整体过程如下所示:
hdu@ubuntu:~/XJFile/make$ ls
hello.c
hdu@ubuntu:~/XJFile/make$ gcc hello.c
hdu@ubuntu:~/XJFile/make$ ls
a.out hello.c
hdu@ubuntu:~/XJFile/make$ ./a.out
Hello World!
hdu@ubuntu:~/XJFile/make$
分步编译
第一步:
gcc -c hello.c
第二步:
gcc -o hello hello.o
hdu@ubuntu:~/XJFile/make$ gcc -c hello.c
hdu@ubuntu:~/XJFile/make$ ls
hello.c hello.o
hdu@ubuntu:~/XJFile/make$ gcc -o hello hello.o
hdu@ubuntu:~/XJFile/make$ ls
hello hello.c hello.o
hdu@ubuntu:~/XJFile/make$ ./hello
Hello World!
hdu@ubuntu:~/XJFile/make$
主程序、子程序链接:子程序编译
编写所需要的主程序、子程序
主程序
#include <stdio.h>
int main()
{
printf("I am father!\n");
Son();
}
子程序
#include <stdio.h>
int Son()
{
printf("I am son!\n");
}
Demo
touch a.h b.h c.h
main.c
#include <stdlib.h>
#include "a.h"
extern void function_two();
extern void function_tree();
int main()
{
function_two();
function_three();
}
2.c
#include "a.h"
#include "b.h"
void function_two(){
}
3.c
#include "b.h"
#include "c.h"
void function_three(){
}
myapp: main.o 2.o 3.o
gcc -o myapp main.o 2.o 3.o
main.o: main.c a.h
gcc -c main.c
2.o: 2.c a.h b.h
gcc -c 2.c
3.o: 3.c b.h c.h
gcc -c 3.c
clean:
rm -f main.o 2.o 3.o
进行程序的编译与链接(Link)
编译
gcc -c father.c son.c
链接
gcc -o out father.o son.o
执行
./out
调用外部函数库:加入链接的函数库
gcc sin.c -lm -L/lib -L/usr/bin
-l: 是加入某个函数库(library)的意思;
m:则是libm.so这个函数库。
-L后面接路径,表示需要的libm.so请到/lib或到/usr/lib里面搜索!