GCC 编译

来源:互联网 发布:集合卡尔曼滤波算法 编辑:程序博客网 时间:2024/05/22 00:54

http://blog.csdn.net/ruglcc/article/details/7814546/

可以参考这个PPT:
http://wenku.baidu.com/link?url=zRKmb2VRhOV6d4DmaAB2zc4-dRwjcbCQlPb2i-ilNiadCI0UQ8UiJZcHoWmKZj2RSL8mwarZprkNdCa8tNDOAOI4aDG500FvuT7vaLyzj0q

可以参考鸟哥的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$ lshello.chdu@ubuntu:~/XJFile/make$ gcc hello.chdu@ubuntu:~/XJFile/make$ lsa.out  hello.chdu@ubuntu:~/XJFile/make$ ./a.outHello World!hdu@ubuntu:~/XJFile/make$

分步编译

第一步:

gcc -c hello.c

第二步:

gcc -o hello hello.o

hdu@ubuntu:~/XJFile/make$ gcc -c hello.chdu@ubuntu:~/XJFile/make$ lshello.c  hello.ohdu@ubuntu:~/XJFile/make$ gcc -o hello hello.ohdu@ubuntu:~/XJFile/make$ lshello  hello.c  hello.ohdu@ubuntu:~/XJFile/make$ ./helloHello 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.omain.o: main.c a.h    gcc -c main.c2.o: 2.c a.h b.h    gcc -c 2.c3.o: 3.c b.h c.h    gcc -c 3.cclean:     rm -f main.o 2.o 3.o

编译

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里面搜索!

0 0
原创粉丝点击