How to search for the readline library with cmake

I'm currently using GNU readline for a RainbruRPG's server tool. Unfortunately, this library isn't shipped with a pkg-config file. We have to create our own cmake file.

First, to confirm the library doesn't have a pkg-config or a cmake file you can try to llist the package file list :
dpkg --listfiles libreadline6-dev | grep .pc
dpkg --listfiles libreadline6-dev | grep .cmake

First, create a cmake/FindReadline.cmake file and copy/paste this code :
# Search for the path containing library's headers
find_path(Readline_ROOT_DIR
    NAMES include/readline/readline.h
)

# Search for include directory
find_path(Readline_INCLUDE_DIR
    NAMES readline/readline.h
    HINTS ${Readline_ROOT_DIR}/include
)

# Search for library
find_library(Readline_LIBRARY
    NAMES readline
    HINTS ${Readline_ROOT_DIR}/lib
)

# Conditionally set READLINE_FOUND value
if(Readline_INCLUDE_DIR AND Readline_LIBRARY 
  AND Ncurses_LIBRARY)
  set(READLINE_FOUND TRUE)
else(Readline_INCLUDE_DIR AND Readline_LIBRARY 
  AND Ncurses_LIBRARY)
  FIND_LIBRARY(Readline_LIBRARY NAMES readline)
  include(FindPackageHandleStandardArgs)
  FIND_PACKAGE_HANDLE_STANDARD_ARGS(Readline DEFAULT_MSG 
    Readline_INCLUDE_DIR Readline_LIBRARY )
  MARK_AS_ADVANCED(Readline_INCLUDE_DIR Readline_LIBRARY)
endif(Readline_INCLUDE_DIR AND Readline_LIBRARY 
  AND Ncurses_LIBRARY)

# Hide these variables in cmake GUIs
mark_as_advanced(
    Readline_ROOT_DIR
    Readline_INCLUDE_DIR
    Readline_LIBRARY
)

Now, go back to your CMakeLists.txt file and tell cmake where to find your custom modules :
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} 
  ${CMAKE_CURRENT_SOURCE_DIR}/cmake)

Finally, search for the readline library and use it in your linking rule :
# Actually search for the library
find_package(Readline)
...
# Use the headers directory
include_directories(${Readline_INCLUDE_DIR})
# Link a target that uses the library
target_link_libraries(my-target-name  ${Readline_LIBRARY})

You can also test for the READLINE_FOUND variable:
if (READLINE_FOUND)
   ...
endif (READLINE_FOUND)

Comments

Popular posts from this blog

Building openmw on Debian Jessie

How to make a clickable label in Gtk2/ruby