Friday, December 7, 2018

Use pkg-config with CMake

Say you want to build a binary which uses OpenCV library. For example, the following would be a typical command for compiling your program
$ g++ `pkg-config --cflags opencv` main.cpp `pkg-config --libs opencv` -o opencv_example

Now, the question is how do we do this with CMake? The following would be what you would write in CMakeLists.txt
project(opencv_example)

# this is where we get pkg-config info
find_package(PkgConfig REQUIRED)
pkg_check_modules(OPENCV REQUIRED opencv)

# this is where you compile your app
add_executable(opencv_example main.cpp)
target_link_libraries(opencv_example ${OPENCV_LIBRARIES})
target_include_directories(opencv_example PUBLIC ${OPENCV_INCLUDE_DIRS})
target_compile_options(opencv_example PUBLIC ${OPENCV_CFLAGS_OTHER})

Happy hacking!