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

參考文檔:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM