目录
一、Gcc生成静态库和动态库
我们通常把一些公用函数制作成函数库,供其它程序使用。函数库分为静态库和动态库两种。静态库在程序编译时会被连接到目标代码中,程序运行时将不再需要该静态库。动态库在程序编译时并不会被连接到目标代码中,而是在程序运行是才被载入,因此在程序运行时还需要动态库存在。
1.Gcc生成静态库
(1)在Ubuntu系统下创建一个目录
- 用文本编辑器编辑生成所需要的 3 个文件。hello.c是函数库的源程序,其中包含公用函数 hello,该函数将在屏幕上输出"HelloXXX!"。hello.h为该函数库的头文件。main.c为测试库文件的主程序,在主程序中调用了公用函数 hello。
- hello.h
#ifndef HELLO_H
#define HELLO_H
void hello(const char *name);
#endif//HELLO_H
- hello.c
#include<stdio.h>
void hello(const char *name)
{
printf("Hello %s\n",name);
}
- main.c
#include"hello.h"
int main()
{
hello("everyone");
return 0;
}
(2)将 hello.c 编译成.o 文件。
(3)创建静态库
- 静态库文件名的命名规范是以 lib 为前缀,紧接着跟静态库名,扩展名为.a。例如:我们将创建的静态库名为 myhello,则静态库文件名就是 libmyhello.a。在创建和使用静态库时,需要注意这点。创建静态库用 ar 命令。在系统提示符下键入以下命令将创建静态库文件libmyhello.a。
(4)在程序中使用静态库
- 方法一:gcc -o hello main.c -L. –lmyhel
- 方法二:gcc main.c libmyhello.a -o hello
- 方法三:先生成 main.o:
gcc -c main.c
再生成可执行文件:
gcc -o hello main.o libmyhello.a
2.由.o 文件创建动态库文件
动态库文件名命名规范和静态库文件名命名规范类似,也是在动态库名增加前缀 lib,但其
文件扩展名为.so。例如:我们将创建的动态库名为 myhello,则动态库文件名就是 libmyh
ello.so。用 gcc 来创建动态库。
(1)新建动态库文件 libmyhello.so。
(2)在程序中使用动态库
- 使用
gcc main.c libmyhello.so -o hello2
,但是接下来./hello 会提示出错,因为虽然连接时用的是当前目录的动态库,但是运行时,是到/usr/lib 中找库文件的,将文件 libmyhello.so 复制到目录/usr/lib 中就 OK 了).程序在运行时,会在/usr/lib 和/lib 等目录中查找需要的动态库文件。若找到,则载入动态库,否则将提示类似上述错误而终止程序运行。我们将文件 libmyhello.so 复制到目录/usr/lib 中。 - 在使用
mv libmyhello.so /usr/lib
需要sudo
命令进入管理员权限。
3.演示实例
代码
main.c
#include"sub1.h"
int main()
{
int x=2,y=9;
printf("%.2f\n",x2x(x,y));
printf("%.2f\n",x2y(x,y));
return 0;
}
sub1.c
#include "sub1.h"
float x2x(int a,int b)
{
float ans;
ans=(float)b/a;
return ans;
}
sub.h
#ifndef SUB_H
#define SUB_H
float x2x(int a,int b);
float x2y(int a,int b);
#endif
sub2.c
float x2y(int a,int b)
{
float c=0;
c=a+b;
return c;
}
linux演示
- 静态库
- 动态库
二、Linux GCC 常用命令
- GCC(GNU C Compiler)是编译工具。本文所要介绍的将 C/C++语言编写的程序转换成为处理器能够执行的二进制代码的过程即由编译器完成。
编译命令
命令 | 示例 |
---|---|
预处理 | gcc -E test.c -o test.i 或 gcc |
编译为汇编代码(Compilation) | gcc -S test.i -o t |
汇编(Assembly) | gcc -c test.s -o test.o |
连接(Linking) | gcc test.o -o test |
多个程序文件的编译 | gcc test1.c test2.c -o test |
检错 | gcc -pedantic illcode.c - |
库文件连接 | gcc main.c libmyhello.so -o hello2 |
编译成可执行文件编译成可执行文件 | gcc –c –I /usr/dev/mysql/include test.c –o |
链接 | gcc –L /usr/dev/mysql/lib –lmysqlclient test.o –o test |
总结
通过使用Gcc生成静态库和动态库可以极大加快编程效率,在这次编程示例中初步了解了静态库和动态库的使用方法和注意事项,同时也学习了Gcc编程的历史和发展过程,拓展了自身视野。