Egor Miroshnichenko
Egor Miroshnichenko

Reputation: 63

cmake: undefined reference to any pcap functions

I want to use pcap in my Clion project on linux. I installed libpcap-dev:

sudo apt-get install libpcap-dev

But then I try to compile any file, containing pcap functions like:

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

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

    dev = pcap_lookupdev(errbuf);
    if (dev == NULL) {
        fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
        return(2);
    }
    printf("Device: %s\n", dev);
    return(0);
}

I have cmake errors:

CMakeFiles/main.cpp.o: In function `main':
/main.cpp:8: undefined reference to `pcap_lookupdev'

I have not used cmake before. Cmake file:

cmake_minimum_required(VERSION 3.7)
project(mypr)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(mypr ${SOURCE_FILES})

Upvotes: 6

Views: 10810

Answers (3)

Sherlei Zhang
Sherlei Zhang

Reputation: 1

I have encounted with a problem similar to this, when I tried to complied with libpcap by ros catkin_make

CMakeFiles/decode_pcap.dir/src/decode_pcap.cpp.o:在函数‘main’中:
decode_pcap.cpp:(.text+0x130):对‘pcap_open_live’未定义的引用
decode_pcap.cpp:(.text+0x1b3):对‘pcap_next’未定义的引用
decode_pcap.cpp:(.text+0x2a4):对‘pcap_loop’未定义的引用
decode_pcap.cpp:(.text+0x2e6):对‘pcap_close’未定义的引用
decode_pcap.cpp:(.text+0x2ff):对‘pcap_close’未定义的引用
collect2: error: ld returned 1 exit status

at last, I added the absolute path to "libpcap.so" by link_libraries() in CMakeLists.txt,like the below

link_libraries(/usr/lib/x86_64-linux-gnu/libpcap.so.0.8)

Upvotes: 0

Nan Xiao
Nan Xiao

Reputation: 17477

I think you can also use CMAKE_MODULE_PATH (assume FindPCAP.cmake is in your project's source directory):

cmake_minimum_required(VERSION 3.7)
project(mypr)

set(CMAKE_CXX_STANDARD 11)

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${PROJECT_SOURCE_DIR}/")

find_package(PCAP REQUIRED)

set(SOURCE_FILES main.cpp)
add_executable(mypr ${SOURCE_FILES})
target_link_libraries(mypr ${PCAP_LIBRARY})

Upvotes: 0

Elvis Teixeira
Elvis Teixeira

Reputation: 614

You should include and use a FindPCAP.cmake file to your CMakeLists.txt. Here is one: https://github.com/bro/cmake/blob/master/FindPCAP.cmake

Put FindPCAP.cmake in your project's source directory and try changing your CMakeLists.txt to:

cmake_minimum_required(VERSION 3.7)
project(mypr)

set(CMAKE_CXX_STANDARD 11)

include(FindPCAP.cmake)

set(SOURCE_FILES main.cpp)
add_executable(mypr ${SOURCE_FILES})
target_link_libraries(mypr ${PCAP_LIBRARY})

Upvotes: 10

Related Questions