Loading

解决 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
      }
    }
  ]
}

参考文档:

posted @ 2022-01-05 17:10  锦瑟,无端  阅读(1886)  评论(0编辑  收藏  举报