在Ubuntu 2.04上如何按照x86_64架构编译libmodbus库

在Ubuntu上按x86_64架构编译libmodbus的核心步骤是使用本地GCC工具链(无需交叉编译),并通过configure脚本指定安装路径

以下是详细流程:

一、安装基础依赖

确保系统已安装编译工具和开发库:

bash 复制代码
sudo apt update
sudo apt install -y automake autoconf libtool gcc make

二、获取并解压源码

从官方仓库下载源码包(以3.1.11版本为例):

bash 复制代码
wget https://libmodbus.org/releases/libmodbus-3.1.11.tar.gz
tar -xzf libmodbus-3.1.11.tar.gz
cd libmodbus-3.1.11

三、生成构建配置(仅Git版本需要)

如果源码未包含configure脚本,运行以下命令生成:

bash 复制代码
./autogen.sh

四、配置编译选项

指定安装路径(示例为/opt/libmodbus_x86_64):

bash 复制代码
./configure \
  --prefix=/opt/libmodbus_x86_64 \  # 安装路径
  --build=x86_64-linux-gnu          # 显式声明架构(可选)

关键参数说明

  • --prefix:控制库和头文件的安装目录
  • --build:明确指定架构(通常可省略,configure会自动检测)

五、编译并安装

bash 复制代码
make -j$(nproc)      # 多线程编译
sudo make install    # 需要root权限写入系统目录

六、验证编译结果

  1. 检查库架构
bash 复制代码
file /opt/libmodbus_x86_64/lib/libmodbus.so*

预期输出

复制代码
ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, ...

测试简单程序

cpp 复制代码
#include <modbus/modbus.h>
#include <stdio.h>

int main() {
    modbus_t *ctx = modbus_new_tcp("127.0.0.1", 1502);
    if (ctx == NULL) {
        fprintf(stderr, "Failed to create context\n");
        return 1;
    }
    printf("Libmodbus x86_64 version: %s\n", LIBMODBUS_VERSION_STRING);
    modbus_free(ctx);
    return 0;
}
bash 复制代码
gcc test_modbus.c -o test_modbus \
  -I/opt/libmodbus_x86_64/include \
  -L/opt/libmodbus_x86_64/lib -lmodbus

export LD_LIBRARY_PATH=/opt/libmodbus_x86_64/lib:$LD_LIBRARY_PATH
./test_modbus

预期输出

复制代码
Libmodbus x86_64 version: 3.1.11

如出现链接错误(未找到库)

临时解决方案:

bash 复制代码
export LD_LIBRARY_PATH=/opt/libmodbus_x86_64/lib:$LD_LIBRARY_PATH

永久解决方案:

bash 复制代码
echo "/opt/libmodbus_x86_64/lib" | sudo tee /etc/ld.so.conf.d/libmodbus_x86_64.conf
sudo ldconfig

关键点总结

步骤 关键命令/参数 作用
配置 ./configure --prefix=/opt/... 指定安装路径
编译 make -j$(nproc) 多线程加速编译
架构验证 file libmodbus.so 确认生成x86_64架构库
运行时路径配置 LD_LIBRARY_PATHldconfig 解决动态库加载问题

通过以上步骤,即可在Ubuntu上成功编译出适用于x86_64架构的libmodbus库。

相关推荐
A小辣椒1 天前
TShark:Wireshark CLI 功能
linux
A小辣椒1 天前
TShark:基础知识
linux
AlfredZhao1 天前
OCI 明明分配了 200G 系统盘,为什么 df 只看到 30G?
linux·oci
AlfredZhao2 天前
vi 删除指定范围的行,不用再反复按 dd
linux·vi
用户9718356334662 天前
银河麒麟 KY10 申威(SW64) 安装 nginx-1.16.1-2.p01.ky10.sw_64.rpm 详细步骤
linux
猪脚踏浪2 天前
linux 拷贝文件或目录到指定的位置
linux
大树883 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠3 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
霸道流氓气质3 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
bush43 天前
嵌入式linux学习记录十四、术语
linux·嵌入式