实例使用库
(1). 创建一个目录
(2). hello代码
hello.h
#ifndef HELLO_H
#define HELLO_H
void hello(const char *name);
#endif
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;
}
编译得到.o文件
静态库的使用
(1)创建静态库
(2)使用静态库
①gcc -o hello main.c -L. -lmyhello
②gcc main.c libmyhello.a -o hello
③先生成 main.o :gcc -c main.c
再生成可执行文件:gcc -o hello main.o libmyhello.a
(3)验证静态库的使用特点
在删掉静态库的情况下,运行可执行文件,发现程序仍旧正常运行,表明静态库是在程序编译的时候被连接到代码中的。
动态库的使用
动态库文件名命名规范和静态库文件名命名规范类似,也是在动态库名增加前缀 lib,但其 文件扩展名为.so。例如:我们将创建的动态库名为myhello,则动态库文件名就是 libmyhello.so。用 gcc 来创建动态库。 在系统提示符下键入以下命令得到动态库文件 libmyhello.so。
(1)创建动态库
创建动态库的工具:gcc
动态库文件命名规范:以lib作为前缀,是.so文件
用rm先将原有的静态库删掉
gcc -shared -fPIC -o libmyhello.so hello.o
shared:表示指定生成动态链接库,不可省略
-fPIC:表示编译为位置独立的代码,不可省略
在程序中执行动态库
gcc -o hello main.c -L. -lmyhello或gcc main.c libmyhello.so -o hello
再运行可执行文件hello,会出现错误,将libmyhello.so复制到目录/usr/lib中。由于运行时,是在/usr/lib中找库文件的
mv libmyhello.so /usr/lib
静态库与动态库比较
gcc编译得到.o文件 gcc -c hello.c
创建静态库 ar -crv libmyhello.a hello.o
创建动态库 gcc -shared -fPIC -o libmyhello.so hello.o
使用库生成可执行文件 gcc -o hello main.c -L. -lmyhello
执行可执行文件 ./hello
实例
sub1.c
float x2x(int a,int b)
{
float c=0;
c=a+b;
return c;
}
sub2.c
float x2y(int a,int b)
{
float c=0;
c=a/b;
return c;
}
sub.h
#ifndef SUB_H
#define SUB_H
float x2x(int a,int b);
float x2y(int a,int b);
#endif
main.c
#include<stdio.h>
#include"sub.h"
void main()
{
int a,b;
printf("Please input the value of a:");
scanf("%d",&a);
printf("Please input the value of b:");
scanf("%d",&b);
printf("a+b=%.2f\n",x2x(a,b));
printf("a/b=%.2f\n",x2y(a,b));
}
gcc -c sub1.c sub2.c