• the includedir (-I) path
    • necessary macro (-D) definitions
    • further required flags (-pthread)
    • the library (-l) to link to

    All current build systems support pkg-config in one way or another. For all examples here we assume you want to compile the sample .

    Using pkg-config in CMake is fairly easy:

    It is generally recommended that you use target_compile_options + _CFLAGS over target_include_directories + _INCLUDE_DIRS as the former includes not just -I flags (GoogleTest might require a macro indicating to internal headers that all libraries have been compiled with threading enabled. In addition, GoogleTest might also require -pthread in the compiling step, and as such splitting the pkg-config Cflags variable into include dirs and macros for target_compile_definitions() might still miss this). The same recommendation goes for using _LDFLAGS over the more commonplace _LIBRARIES, which happens to discard -L flags and -pthread.

    Let’s say you have a CMakeLists.txt along the lines of the one in this tutorial and you try to run cmake. It is very possible that you get a failure along the lines of:

    1. -- Checking for one of the modules 'gtest_main'
    2. CMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message):
    1. export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig

    pkg-config will also try to look in PKG_CONFIG_PATH to find gtest_main.pc.

    Pkg-config can be used in a cross-compilation setting too. To do this, let’s assume the final prefix of the cross-compiled installation will be /usr, and your sysroot is /home/MYUSER/sysroot. Configure and install GTest using

    Install into the sysroot using DESTDIR:

    1. make -j install DESTDIR=/home/MYUSER/sysroot

    Before we continue, it is recommended to always define the following two variables for pkg-config in a cross-compilation setting:

    1. export PKG_CONFIG_ALLOW_SYSTEM_LIBS=yes

    If you look at the generated pkg-config file, it will look something like

    Notice that the sysroot is not included in libdir and includedir! If you try to run pkg-config with the correct PKG_CONFIG_LIBDIR=/home/MYUSER/sysroot/usr/lib64/pkgconfig against this .pc file, you will get

    1. $ pkg-config --cflags gtest
    2. -DGTEST_HAS_PTHREAD=1 -lpthread -I/usr/include
    3. $ pkg-config --libs gtest
    4. -L/usr/lib64 -lgtest -lpthread

    which is obviously wrong and points to the CBUILD and not CHOST root. In order to use this in a cross-compilation setting, we need to tell pkg-config to inject the actual sysroot into -I and -L variables. Let us now tell pkg-config about the actual sysroot

    1. export PKG_CONFIG_DIR=
    2. export PKG_CONFIG_LIBDIR=${PKG_CONFIG_SYSROOT_DIR}/usr/lib64/pkgconfig

    and running again we get