You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为ARMv7交叉编译含libpcap的C程序遇文件格式错误求助

交叉编译libpcap程序时出现"file format not recognized"错误的解决方法

问题背景

以下是用于SAMA5D2开发板的简单pcap抓包程序:

#include <stdio.h>
#include <pcap.h>

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

    pcap_t *handle;
    handle = pcap_open_live(NULL, BUFSIZ, 1, 1000, errbuf);
    if (handle == NULL) {
        fprintf(stderr, "Couldn't open device: %s\n", errbuf);
        return(2);
    }

    struct pcap_pkthdr header;
    const u_char *packet;
    packet = pcap_next(handle, &header);
    /* Print its length */
    printf("Jacked a packet with length of [%d]\n", header.len);
    /* And close the session */
    pcap_close(handle);

    return(0);
}

交叉编译步骤如下:

  1. 下载并交叉编译libpcap:
wget https://github.com/the-tcpdump-group/libpcap/archive/libpcap-1.9.1.tar.gz
tar zxf libpcap-1.9.1.tar.gz
cd libpcap-libpcap-1.9.1
CROSS_COMPILE=arm-linux-gnueabihf- CC=${CROSS_COMPILE}gcc ./configure --host=arm-linux-gnueabihf --prefix=$(pwd)/libpcap-1.9.1-arm-linux-gnueabihf
CROSS_COMPILE=arm-linux-gnueabihf- CC=${CROSS_COMPILE}gcc make install
  1. 编译应用程序:
arm-linux-gnueabihf-gcc program_pcap.c -lpcap -L./libpcap-libpcap-1.9.1/libpcap-1.9.1-arm-linux-gnueabihf/lib

出现错误:

./libpcap-libpcap-1.9.1/libpcap-1.9.1-arm-linux-gnueabihf/lib/libpcap.so: file not recognized: file format not recognized
collect2: error: ld returned 1 exit status

问题原因

错误核心是libpcap.so的文件架构与目标ARM平台不匹配,大概率是交叉编译配置未生效,导致生成的库是主机(x86)架构而非ARM架构。

解决步骤

1. 验证库文件架构

先确认生成的库是否为ARM架构:

file ./libpcap-libpcap-1.9.1/libpcap-1.9.1-arm-linux-gnueabihf/lib/libpcap.so

如果输出包含x86-64或类似x86相关描述,说明交叉编译失败。

2. 重新交叉编译libpcap

清理之前的编译残留,重新配置并编译,确保交叉编译工具链正确生效:

cd libpcap-libpcap-1.9.1
# 清理残留文件
make clean && rm -rf config.cache config.log config.status
# 导出交叉编译环境变量
export CROSS_COMPILE=arm-linux-gnueabihf-
export CC=${CROSS_COMPILE}gcc
# 重新配置
./configure --host=arm-linux-gnueabihf --prefix=$(pwd)/libpcap-1.9.1-arm-linux-gnueabihf
# 编译安装
make && make install

注意:将环境变量单独导出,避免shell解析命令时出现变量未生效的问题。

3. 修正应用程序编译命令

编译时需指定头文件路径,同时确保链接库的参数放在源文件之后(链接器按顺序解析符号):

arm-linux-gnueabihf-gcc program_pcap.c -I./libpcap-libpcap-1.9.1/libpcap-1.9.1-arm-linux-gnueabihf/include -L./libpcap-libpcap-1.9.1/libpcap-1.9.1-arm-linux-gnueabihf/lib -lpcap -o program_pcap

4. 额外检查项

  • 确认交叉编译工具链正常工作:运行arm-linux-gnueabihf-gcc -v,查看输出是否包含ARM相关架构信息。
  • 若configure时提示缺少flex或bison,需先安装依赖:sudo apt install flex bison(Debian/Ubuntu系统)。

内容的提问来源于stack exchange,提问作者Yosef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:45:56