Redis++ is the recommended C++ binding for connecting to a Redis server from a C++ application, however its build script is not entirely friendly towards CMake. It relies upon hiredis, but the make script expects it to already be compiled on the system.
To compile hiredis as part of your own CMake script, add the following:
# Download Hiredis, upon which Redis Plus Plus depends.
FetchContent_Declare(
hiredis
GIT_REPOSITORY https://github.com/redis/hiredis
GIT_TAG v1.1.0
SOURCE_DIR hiredis
)
FetchContent_MakeAvailable(hiredis)
# Download the Redis binding.
FetchContent_Declare(
redis_plus_plus
GIT_REPOSITORY https://github.com/sewenew/redis-plus-plus
GIT_TAG 1.3.8
)
# Pre-fill the include and library paths so that Redis++ does not search for them.
set(CMAKE_INCLUDE_PATH "${CMAKE_INCLUDE_PATH};${hiredis_SOURCE_DIR}")
set(TEST_HIREDIS_LIB "${hiredis_BINARY_DIR}/libhiredisd.a")
set(HIREDIS_LIB "${hiredis_BINARY_DIR}/libhiredisd.a")
FetchContent_MakeAvailable(redis_plus_plus)
# ... include your own source files here.
# Add the Redis++ include directory.
target_include_directories(myTarget PRIVATE "${redis_plus_plus_SOURCE_DIR}/src")
# Link with Redis++ and Hiredis.
target_link_libraries(myTarget PRIVATE redis++::redis++_static)
target_link_libraries(myTarget PRIVATE hiredis::hiredis_static)
This operates as follows:
FetchContent_Declare(hiredis ...)
creates the hiredis
target, and then FetchContent_MakeAvailable(hiredis)
causes the files to actually be downloaded. The SOURCE_DIR hiredis
option is required because Redis++ expects the include file to be in "hiredis/hiredis.h"
, and by default CMake will use the directory hiredis-src
not hiredis
.
FetchContent_Declare(redis_plus_plus ...)
creates the redis_plus_plus
target, however the CMake script for Redis++ assumes that hiredis
has already been compiled and installed at this point, so it checks for the hiredis header file and library file, and fails if the do not exist.
Because we are controlling the compilation of hiredis
, we know the destination that the library will be built to, and so we can pre-fill the include and library paths, making Redis++ skip searching for them.
The Redis++ CMake script can then be executed as normal.
The final step is to link with the generated libraries. For dynamic linking, simply remove the _static
suffix and change the library name in HREDIS_LIB
& TEST_HREDIS_LIB
to libhiredisd.so
.
Note that the Hiredis library must be added after the Redis++ library.