c++cmakelibevent

Can't compile code with libevent library using CMake


I use CMake in VS Code to build project with libevent. I add it to project

find_package(LIBEVENT REQUIRED)

target_link_libraries(${PROJECT_NAME}
  PUBLIC
  ${LIBEVENT_LIB}
)

target_include_directories(${PROJECT_NAME}
  PUBLIC
  ${LIBEVENT_INCLUDE_DIR}
)

And pass -levent flag to linker

target_link_options(TEST-CMAKE PUBLIC "-L/E:/Projects/C++/.libraries/libevent-2.1.12-stable/build/lib -levent -levent_core")

if i don't use any functions in code it compiles without errors, but if i use some, it fails with error

undefined reference to `event_base_dispatch' (same with other functions)

I found that problem might be in flag order, but i don't know how to change it in cmake

code i try to compile

#include <iostream>
#include <event2/event.h>
int main()
{    
    
    event_base* evbase;
    event_base_dispatch(evbase);
}

I have Windows 10, GCC 11.3.0

CMakeLists.txt

cmake_minimum_required(VERSION 3.0.2)
project(TEST-CMAKE VERSION 0.1.0)

include(CTest)
enable_testing()

add_executable(TEST-CMAKE main.cpp)

find_package(LIBEVENT REQUIRED)

target_include_directories(${PROJECT_NAME}
  PUBLIC
  ${LIBEVENT_INCLUDE_DIR}
)

target_link_libraries(${PROJECT_NAME}
  PUBLIC
  ${LIBEVENT_LIB}
)

target_link_options(TEST-CMAKE PUBLIC "-L/E:/Projects/C++/.libraries/libevent-2.1.12-stable/build -levent -levent_core")

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)

Solution

  • With find_package https://github.com/libevent/libevent/blob/master/cmake/LibeventConfig.cmake.in#L8 you should be able to just:

    find_package(Libevent REQUIRED)
    add_executable(TEST-CMAKE main.cpp)
    target_link_libraries(TEST-CMAKE libevent::core)