1

I have a program that I want to use pcap_create() in, but before I use this API, I want to ensure this API exists. I know in version 1.0 of libpcap this API exists, but how can I check the version of libpcap at compile time?

For example, I want something like the below:

#if PCAP_MAJOR_VERSION >= 1
pcap_create(...
#else
pcap_open_live(...
#endif
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sorosh_sabz
  • 2,356
  • 2
  • 32
  • 53

1 Answers1

1

You don't actually care about the library version, you care about whether or not the symbol pcap_create is present. Therefore, this is a job for CheckSymbolExists:

# This assumes PCAP_INCLUDE_DIRS is appropriately set somehow, maybe via:
#
#     find_path(PCAP_INCLUDE_DIRS "pcap/pcap.h")
#
# or something else in your CMakeLists.txt

include(CheckSymbolExists)

set(CMAKE_REQUIRED_INCLUDES "${PCAP_INCLUDE_DIRS}")
check_symbol_exists(pcap_create "pcap/pcap.h" HAVE_PCAP_CREATE)

add_executable(main main.cpp)
target_compile_definitions(main PRIVATE "HAVE_PCAP_CREATE=$<BOOL:${HAVE_PCAP_CREATE}>")

This will define HAVE_PCAP_CREATE in main.cpp to 1 or 0 if the pcap_create function exists or not. Then in your code you would write:

#if HAVE_PCAP_CREATE
pcap_create(...);
#else
pcap_open_live(...);
#endif
Alex Reinking
  • 16,724
  • 5
  • 52
  • 86
  • Thanks for answer my question, so Did you say libpcap does not provide any pre-compile version macro something like [__GNUC_PREREQ](https://stackoverflow.com/a/259279/1539100)? or you just say, the best way (best practice) to check API exist in the third party library, is checking symbol? – sorosh_sabz Jun 24 '21 at 08:36