Linux下动、静态库的创建和调用

静态库

linux静态库命名规则:
image

静态库的创建

准备工作:
以一个简单的计算器demo为例,首先建立并书写以下三个文件:
image

  • Math.h 声明四则基本运算
#ifndef __MATH_H__
#define __MATH_H__
double add(double a,double b);
double sub(double a,double b);
double mul(double a,double b);
double div(double a,double b);
#endif
  • Math.cpp 定义四则运算的接口
#include "Math.h"
double add(double a,double b)
{
	return a+b;
}

double sub(double a,double b)
{
	return a-b;
}

double mul(double a,double b)
{
	return a*b;
}

double div(double a,double b)
{
	return a/b;
}
  • main.cpp 具体接口的使用
#include "Math.h"
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{

    double a = 10;
    double b = 2;

    cout << "a + b = " << add(a, b) << endl;

    cout << "a - b = " << sub(a, b) << endl;

    cout << "a * b = " << mul(a, b) << endl;

    cout << "a / b = " << div(a, b) << endl;

    return 0;
}

静态库的创建步骤
1.将需要包含入库的文件编译成二进制文件

//默认生成 目标名称.o
g++ -c Math.cpp [-o Math.o]

2.使用ar工具打包静态库

ar -crv libmath.a Math.o 

生成静态库 libmath.a(库名math) 即可

静态库的使用

g++ main.cpp -L/home/lsq/my_lab/math(静态库存放的路径) -lmath(静态库名(无前后缀))
  • 使用运行文件
    image

动态库

linux动态库命名规则:
image

动态库的创建

仍用计算器demo的三个文件main.cpp, Math.h, Math.cpp来操作:
动态库的创建步骤
1.将需要包含入库的文件编译成二进制文件

g++ -fPIC -c Math.cpp

-fPIC 创建与地址无关的编译程序(pic,position independent code),是为了能够在多个应用程序间共享。
2.动态链接库

g++ -shared -o libdynmath.so Math.o

-shared 生成动态链接库文件

  • 也可以一步完成
g++ -fPIC -shared -o libdynmath.so Math.cpp

动态库的调用

与静态库调用相同

g++ main.cpp -L/home/lsq/my_lab/math(动态库存放的路径) -ldynmath(动态库名(无前后缀))

在调用之前需要让执行程序定位共享库文件!!!否则无法运行
两种方法:

  • 将库文件 libdynmath.so 安装到 默认路径(\lib或者\usr\lib) 即可;
  • 将其添加到 /etc/ld.so.cache 文件中,步骤如下:(注意权限!!!)
    1.将库文件存在的路径加到 \etc\ld.so.conf 中;
    2.ldconfig 重新加载 ld.so.cache 文件;

定位库文件后,即可运行程序

image

posted @ 2023-01-04 15:36  _神奇海螺  阅读(238)  评论(0编辑  收藏  举报