UbuntuV24.04安装mpdecimal库(libmpdec),从源码编译
目录
〇 简介
一 下载源码,编译安装libmpdec
二 安装完成后让系统加载
三 编写测试文件test_mpdec.c
四 编译测试程序
五 运行测试
〇 简介
python安装构建-官方文档
在Ubuntu下安装python时,要安装python的依赖库,可选模型中 Ubuntu 24.04 没有 libmpdec-dev
包
you can install the build dependencies via apt
:
$ sudo apt-get build-dep python3 $ sudo apt-get install pkg-config
If you want to build all optional modules, install the following packages and their dependencies:
$ sudo apt-get install build-essential gdb lcov pkg-config \libbz2-dev libffi-dev libgdbm-dev libgdbm-compat-dev liblzma-dev \libncurses5-dev libreadline6-dev libsqlite3-dev libssl-dev \lzma lzma-dev tk-dev uuid-dev zlib1g-dev libzstd-dev
Debian 12 and Ubuntu 24.04 do not have the libmpdec-dev
package. You can safely remove it from the install list above and the Python build will use a bundled version. But we recommend using the system libmpdec library. Either built it from sources or install this package from https://deb.sury.org.
以下讲解从源码编译安装libmpdec库及简单测试的方法。
一 下载源码,编译安装libmpdec
#!/bin/bash# 更新系统包列表
sudo apt update# 安装必要的构建工具和依赖库
sudo apt install -y build-essential autoconf automake libtool pkg-config# 创建一个临时目录来存放下载的文件
TEMP_DIR=$(mktemp -d)
cd "$TEMP_DIR"# 下载 libmpdec 的最新版本源码
wget https://www.bytereef.org/software/mpdecimal/releases/mpdecimal-2.5.1.tar.gz# 解压源码包
tar xzf mpdecimal-2.5.1.tar.gz
cd mpdecimal-2.5.1# 配置编译选项
./configure --prefix=/usr/local# 编译源码
make# 安装编译好的库
sudo make install# 清理临时文件
cd ..
rm -rf "$TEMP_DIR"
二 安装完成后让系统加载
库文件通常位于 /usr/local/lib 或 /usr/local/lib/x86_64-linux-gnu。
头文件通常位于 /usr/local/include。
执行 ldconfig 重建系统动态链接库缓存
三 编写测试文件test_mpdec.c
#include <stdio.h>
#include <mpdecimal.h>int main() {// 设置 decimal 上下文,指定精度为 20 位mpd_context_t ctx;mpd_init(&ctx, 20); // 20 位精度// 创建两个 decimal 数mpd_t *a = mpd_new(&ctx);mpd_t *b = mpd_new(&ctx);mpd_t *result = mpd_new(&ctx);// 设置值:a = 1.23456789, b = 9.87654321mpd_set_string(a, "1.23456789", &ctx);mpd_set_string(b, "9.87654321", &ctx);// 执行加法:result = a + bmpd_add(result, a, b, &ctx);// 打印结果char *output = mpd_to_sci(result, 1); // 科学计数风格,1 表示带符号printf("Result of 1.23456789 + 9.87654321 = %s\n", output);// 释放内存free(output);mpd_del(a);mpd_del(b);mpd_del(result);return 0;
}
四 编译测试程序
由于是从源码编译安装的 libmpdec,而不是通过系统包管理器(比如 apt)安装的,因此:
编译时必须手动告诉 gcc libmpdec 的头文件路径 和 库文件路径
gcc test_mpdec.c -o test_mpdec \-I/usr/local/include \-L/usr/local/lib \-lmpdec
五 运行测试
./test_mpdec
看到结果
Result of 1.23456789 + 9.87654321 = 11.11111110