我測試 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