您的位置:首页 > 运维架构 > Linux

linux下程序开发的基本概念

2010-09-24 16:41 429 查看
首先,我们认识几个目录。头文件,位于/usr/include目录。头文件包含有常量定义、系统调用和库函数调用的声明。这是系统默认的头文件存放路径,在编译程序时,编译器会自动查找该目录。gcc编译器在编译程序时也可用-I参数指定另外的头文件路径。如:gcc -l /usr/local/myinclude test.h

库文件,库是一组已编译的函数集合,可方便我们重用代码。默认存放在/lib和/usr/lib目录。库文件可分为静态和共享两类。

.a,静态库文件。使用静态库将会把所有的库代码引入程序,占用更多的磁盘空间和内存空间,所以一般建议使用共享库。

.so,共享库文件。使用共享库的程序不包含库代码,只在程序运行才调用共享库中的代码。

在编译时可用包含路径的库文件名或用-l参数指定使用的库文件,/usr/lib/libm.a等价于-lm。如:gcc -o hello hello.c /usr/lib/libm.a

或用-l参数写成 gcc -o hello hello.c -lm ,如果我们要使用的库文件不在默认位置,在编译程序时可用-L参数指定库文件的路径。

下面通过编写一个静态库实现函数功能的例子来具体说明。

分别创建两个函数,函数a的内容如下:

#include <stdio.h>
void a(char *arg)
{
printf("function a,hello world %s/n",arg);
}


函数b的内容如下:

#include <stdio.h>
void b(int arg)
{
printf("function b,hello world %d/n",arg);
}


接着,分别生成目标文件a.o和b.o

$ gcc -c a.c b.c

$ls *.o

a.o b.o

最后,用ar归档命令把生成的对象文件打包成一个静态库libhello.a。

$ ar crv libhello.a a.o b.o

a - a.o

a - b.o

为我们的静态库定义一个头文件libhello.h,包含这两个函数的定义。
/*
*this is a header file.
*/
void a(char *arg);
void b(int arg);
extern void a(char *arg)
{
printf("function a,hello world %s/n",arg);
}
extern void b(int arg)
{
printf("function b,hello world %d/n",arg);
}

最后,创建测试程序hello.c
#include <stdio.h>
#include <stdlib.h>
#include "libhello.h"
int main()
{
a("heqiang");
b(3);
exit(0);
}

利用静态链接库编译程序:
$gcc -c hello.c
$ gcc -o hello hello.o libhello.a

$ ./hello

function a,hello world heqiang
function b,hello world 3

从上面这个例子我们看到了程序从源文件(.c)文件经过预处理,编译,汇编生成了.o文件,然后通过链接静态库文件生成可执行程序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐