静态库
1.先准备.c文件。
one.c
#include <stdio.h>
//冒泡排序
void BubbleSort(int arry[],int len)
{
int i;
int j;
int temp;
for(i=0;i<len-1;i++)//比较次数
{
for(j=0;j<len-1-i;j++)//比较过程
{
if(arry[j]>arry[j+1]) //比较大小
{
temp=arry[j];
arry[j]=arry[j+1];
arry[j+1]=temp;
}
}
}
}
//输出
void print(int arry[],int len)
{
int i;
for(i=0;i<len;i++)
{
printf("%d ",arry[i]);
}
}
two.c
#include <stdio.h>
//选择排序
void selectSort(int arry[], int len)
{ int i;
int j;
for ( i = 0; i < len-1; i++)
{
int min = i;//假设第一个元素是最小的
for (j = i + 1; j < len; j++)
{
if (arry[j] < arry[min])
{
min = j;//保存最小元素的下标
}
}
//交换
int temp = arry[min];
arry[min] = arry[i];
arry[i] = temp;
}
}
three.c
#include <stdio.h>
//插入排序
void insertSort(int arry[], int len)
{
int i;
int temp;//保存要插入的元素
int j;//从当前要要比较插入的元素的前面一个开始
for ( i = 1; i < len; i++)//第一个元素视为有序,把后面的元素一个一个的插入到前面
{
temp = arry[i];
j = i - 1;
while (j >= 0&&arry[j]>temp)
{
arry[j + 1] = arry[j];//前面的元素往后面移动
j--;
}
arry[j + 1] = temp;//把要插入的元素,插入进对应的位置
}
}
2.准备主函数
main.c
#include<stdio.h>
#include "head.h"
int main()
{
int arry[10]={3,44,38,5,47,15,36,26,27,2};
BubbleSort(arry,10);
print(arry,10);
printf("\n");
selectSort(arry,10);
print(arry,10);
printf("\n");
insertSort(arry,10);
print(arry,10);
printf("\n");
return 0;
}
3.接口,调用各函数的方法
head.h
#ifndef _HEAD_H
#define _HEAD_H
//maopaopaixu
void BubbleSort(int arry[],int len);
void print(int arry[],int len);
//xuanzhepaixu
void selectSort(int arry[],int len);
void print(int arry[],int len);
//charupaixu
void insertSort(int arry[],int len);
void print(int arry[],int len);
#endif
生成静态库
1.将三个.c文件变成.o文件
gcc -c one.c two.c three.c
ar -crv jtku.a one.o two.o three.o
gcc -c main.c
gcc -o four main.o jtku.a
./four
./four运行成功静态库就能运用了并建立成功 ,这里four文件是执行文件,静态库是jtku.a。
(我编译生成静态库的时候出现错误,是虚拟机本身没有安装静态库的包,后来找了方法下载静态库就可以用了。)
生成动态库
同样生成动态库也出现了错误,如下usr/bin/ld: one.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
one.o: error adding symbols: 错误的值
collect2: 错误:ld 返回 1
解决方法:
编译时加上-fPIC
gcc -c -fPIC one.c two.c three.c
gcc -shared -fPIC -o dtku.so one.o two.o three.o
gcc -c main.c
gcc -o five main.o ./dtku.so
./five
./five执行成功,说明动态库成功可运用。
动态库是dtku.so文件,five是执行文件。
代码和方法都是上网找的,写在这里就是怕以后忘记 ,也是找点事干。