编译生成静态库:
1.编写CPP文件test.h
#include <iostream>
using namespace std;
class ADD_SUB{
public:
int add(int a, int b){
cout << "a + b = " << a + b << endl;
return a + b;
}
int sub(int a, int b){
cout << "a - b = " << a - b << endl;
return a - b;
}
};
2.编译
g++ -o test.out -c test.h
3.生成
ar -cr libtest.a test.out
4.调用libtest.a的main函数如下:
#include <iostream>
#include "test.h"
using namespace std;
void main(){
ADD_SUB as;
as.add(1,3);
as.sub(1,3);
}
5.编译
main.cpp: g++ main.cpp
6.运行:
./a.out
C++生成动态库
1.编写如生成静态库一样的test.h文件。
2.编译
g++ -shared -fPIC -o libtest.so test.h
3.调用libtest.so的main函数与静态库一样
4.编译
g++ -o main.out main.cpp
5.运行测试
./main.out
本文介绍了如何在Ubuntu Linux环境下使用C++编译生成自定义的静态库(libtest.a)和动态库(libtest.so)。通过编写test.h文件,然后进行编译和链接步骤,详细阐述了生成及调用这两个库的过程,包括main函数的编写和测试运行。

993

被折叠的 条评论
为什么被折叠?



