目录
一.hello实例准备库
1.准备过程
(1). 创建一个目录
(2). 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;
}
gcc编译得到.o文件
2.静态库的使用
创建静态库 :ar
静态库文件命名规范:以lib作为前缀,是.a文件
ar -crv libmyhello.a hello.
程序中使用静态库
gcc -o hello main.c -L. -lmyhello
gcc main.c libmyhello.a -o hello
先生成main.o gcc -c main.c
生成可执行文件 gcc -o hello main.c libmyhello.a
2.动态库
创建动态库
创建动态库的工具:gcc
动态库文件命名规范:以lib作为前缀,是.so文件
二.实例使用库
1.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));
}
2.静态库
ar crv libsub.a sub1.o sub2.o
3.动态库
gcc -shared -fPIC -o libsub.so sub1.o sub2.o
gcc -o main main.c libsub.so