文章目录
- 作用
- 分离编译(防止拷贝源码,用二进制文件,直接调用)
- 代码重用
- 分类
分类 | 作用 | 后缀 |
---|---|---|
静态库 | 一个或多个.o 目标文件归档在一个文件中+头文件 |
.a |
共享库 | 没有main 函数的可执行文件 |
.so |
动态加载库 | 没有main 函数的可执行文件,接口复合API |
.so |
0.前提(文件内容)
1.准备:将原来的array.h,array.cpp拆分成两个文件;
array.h, alg.h,array.cpp, alg.cpp
array.h
#ifndef __ARRAY_H
#define __ARRAY_H
#ifdef __cplusplus
extern "C"{
#endif // __cplusplus
void* seq_create();
void seq_destroy(void* seq);
void seq_append(void* seq,int val);
void seq_prepend(void* seq,int val);
int seq_size(void* seq);
int seq_get(void* seq,int index);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // __ARRAY_H
- alg.h
#ifndef __ALG_H
#define __ALG_H
#ifdef __cplusplus
extern "C"{
#endif // __cplusplus
// C语言不认识extern "C"
int sum(int* arr,int n);
void reverse(int* arr,int n);
int max_element(int* arr,int n);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // __ALG_H
array.cpp
//#include "vector.h"
#include <vector>
#include "array.h"
using namespace std;
//using namespace miniSTL;
void* seq_create(){
return new vector<int>();
}
void seq_destroy(void* seq){
delete reinterpret_cast<vector<int>*>(seq);
}
void seq_append(void* seq,int val){
reinterpret_cast<vector<int>*>(seq)->push_back(val);
}
void seq_prepend(void* seq,int val){
vector<int>* p = reinterpret_cast<vector<int>*>(seq);
p->insert(p->begin(),val);
}
int seq_size(void* seq){
return reinterpret_cast<vector<int>*>(seq)->size();
}
int seq_get(void* seq,int index){
return reinterpret_cast<vector<int>*>(seq)->at(index);
}
alg.cpp
#include "alg.h"
#include <algorithm>
#include <numeric>
using namespace std;
int sum(int* arr,int n){
return accumulate(arr,arr+n,0);
}
void reverse(int* arr,int n){
reverse(arr,arr+n);
}
int max_element(int* arr,int n){
return max_element(arr,arr+n) - arr;
}
- array_test.cpp
#include "array.h"
#include "alg.h"
#include <iostream> // 在CPP不使用io
#include <algorithm>
using namespace std;
int main(){
int arr[] = {
1,3,6,2,7};
cout << sum(arr,5) << endl;
for_each(arr,arr+5,[](int n){
cout