pkg-config variables in CMake

pkg-config is a freedesktop standard and implementation that helps developers finding correct compile and link flags of dependencies. Despite its very low version number, it is the de facto method for determining said flags on the Linux desktop. An oft-forgotten feature of pkg-config is the ability of a package to expose arbitrary key-value meta data. This allows dependent applications to find data paths, plugins to know where to install themselves or determining tool paths.

Although CMake supports pkg-config for quite some time with its FindPkgConfig module, it only queries for the compile and link information. If you want to get a variable value you are out of luck. But fear not! Just stick this into a CMake module

find_package(PkgConfig REQUIRED)

function(pkg_check_variable _pkg _name)
    string(TOUPPER ${_pkg} _pkg_upper)
    string(TOUPPER ${_name} _name_upper)
    string(REPLACE "-" "_" _pkg_upper ${_pkg_upper})
    string(REPLACE "-" "_" _name_upper ${_name_upper})
    set(_output_name "${_pkg_upper}_${_name_upper}")

    execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} --variable=${_name} ${_pkg}
                    OUTPUT_VARIABLE _pkg_result
                    OUTPUT_STRIP_TRAILING_WHITESPACE)

    set("${_output_name}" "${_pkg_result}" CACHE STRING "pkg-config variable ${_name} of ${_pkg}")
endfunction()

and you can easily query information like this

pkg_check_modules(GLIB glib-2.0)
pkg_check_variable(glib-2.0 glib-genmarshal)
message("Path: ${GLIB_2.0_GLIB_GENMARSHAL}")