How to Link libdav1d Dynamically with CMake
Linking the libdav1d AV1 decoder dynamically in a CMake
project is best achieved using modern CMake practices. This article
explains how to locate the dynamic library on a system using
pkg-config via CMake’s FindPkgConfig module,
define the imported target, and properly link it to your executable or
library.
The Recommended Approach: FindPkgConfig
Because libdav1d is built using the Meson build system,
it does not ship with CMake-specific configuration files (like
dav1dConfig.cmake). Instead, it installs a
pkg-config file (dav1d.pc).
The standard and most reliable way to locate and link
libdav1d dynamically in CMake is by using the
FindPkgConfig module to locate this .pc
file.
Step-by-Step Implementation
- Enable PkgConfig support in your
CMakeLists.txt. - Locate the dav1d library using
pkg_check_modules. - Link the imported target to your project using
target_link_libraries.
Here is a complete, minimal CMakeLists.txt example
demonstrating this setup:
cmake_minimum_required(VERSION 3.12)
project(Dav1dDecoderProject C)
# 1. Find the PkgConfig tool
find_package(PkgConfig REQUIRED)
# 2. Search for libdav1d and create an imported target
# The 'IMPORTED_TARGET' option automatically creates 'PkgConfig::DAV1D'
pkg_check_modules(DAV1D REQUIRED IMPORTED_TARGET dav1d)
# 3. Define your executable or library
add_executable(my_decoder main.c)
# 4. Link the dynamic libdav1d target
target_link_libraries(my_decoder PRIVATE PkgConfig::DAV1D)Why This Method Works Best for Dynamic Linking
- Automated Flags: The
PkgConfig::DAV1Dimported target automatically manages the correct compiler include directories, preprocessor definitions, and linker flags required for dynamic linking on your target platform. - Shared Library Preference: By default,
pkg_check_modulesresolves to the shared library (.soon Linux,.dylibon macOS,.dllon Windows), ensuring dynamic linking. - Cross-Platform Compatibility: This method is standard across Unix-like operating systems, including Linux, BSD, and macOS (via Homebrew/MacPorts), as well as Windows environments using MSYS2 or MinGW.