解决 libpcap 出现 "undefined reference" 问题


我测试 libpcap 的源码

void parse_pacp()
{
    char errbuf[PCAP_ERRBUF_SIZE] = "";     // PCAP_ERRBUF_SIZE 为 512 字节
    // const char* dir = "****";

    pcap_t *pcap_ptr = pcap_open_offline( dir, errbuf);
    if(!pcap_ptr)
        cout << " open pcap file faied ~" << endl;
    else
        cout << " open pcap file success ~ " << endl;

    pcap_close(pcap_ptr);
}

执行 parse_pcap 函数会报错:

  • undefined reference to `pcap_open_offline'
  • undefined reference to `pcap_close'

明显链接时问题,查了相关问题后基本上都是在编译运行命令后加上参数 -lpcap就行,即:

g++ pcap_parse.cc -o pcap_parse -lpcap

注意: -lpcap 要加在最后面,同时也可以通过 -L参数指定位置,不过没必要

由于我在 ubuntu 下都是用的 vscode,而 vscode 可以通过 tasks.json 配置编译运行时命令的组成情况,因此我直接将 -lpcap 加在该项目的 task.json 中,vscode 直接执行成功。

// ubuntu
{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "shell",
      "label": "g++ build active file",
      "command": "/usr/bin/g++",
      "args": [
        "-g",
        "${file}",
        "-o",
        "${fileDirname}/${fileBasenameNoExtension}",
        "-lpcap"
      ],
      "options": {
        "cwd": "/usr/bin"
      },
      "problemMatcher": [
        "$gcc"
      ],
      "group": {
        "kind": "build",
        "isDefault": true
      }
    }
  ]
}

参考文档:

  • Pcap functions have "undefined reference"https://stackoverflow.com/questions/27107998/pcap-functions-have-undefined-reference
  • Why does the order in which libraries are linked sometimes cause errors in GCC?https://stackoverflow.com/questions/45135/why-does-the-order-in-which-libraries-are-linked-sometimes-cause-errors-in-gcc
  • proj.c:(.text+0x140): undefined reference to `pcap_open_offline'https://stackoverflow.com/questions/46920975/proj-c-text0x140-undefined-reference-to-pcap-open-offline