'libavformat fails to link on Macos

I'm trying to go through an ffmpeg tutorial however when I try to build my project I get the following error. I initialy thought that cmake's find_path and find_library was linking the wrong files Mark Setchell showed that this was not the case. Now I'm not sure why the linker errors are occurring. Here is the minimum example that fails to compile and the aforementioned error.

[build] [1/1 100% :: 0.076] Linking CXX executable example
[build] FAILED: example 
[build] : && /usr/bin/clang++ -g -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -L/usr/local/opt/llvm/lib CMakeFiles/example.dir/main.cpp.o -o example  /usr/local/lib/libavformat.dylib && :
[build] Undefined symbols for architecture x86_64:
[build]   "avformat_open_input(AVFormatContext**, char const*, AVInputFormat const*, AVDictionary**)", referenced from:
[build]       _main in main.cpp.o
[build]   "avformat_free_context(AVFormatContext*)", referenced from:
[build]       _main in main.cpp.o
[build]   "avformat_alloc_context()", referenced from:
[build]       _main in main.cpp.o
[build] ld: symbol(s) not found for architecture x86_64
[build] clang: error: linker command failed with exit code 1 (use -v to see invocation)
[build] ninja: build stopped: subcommand failed.

CMakeLists.txt:

cmake_minimum_required(VERSION 3.21)
set(CMAKE_CXX_STANDARD 17)


find_path(AVFORMAT_INCLUDE_DIRS libavformat/avformat.h REQUIRED)
find_library(AVFORMAT_LIBRARY avformat REQUIRED)

message(WARNING "AVFORMAT_LIBRARY=" ${AVFORMAT_LIBRARY})
message(WARNING "AVFORMAT_INCLUDE_DIRS=" ${AVFORMAT_INCLUDE_DIRS})

add_executable(example main.cpp)
target_link_libraries(example ${AVFORMAT_LIBRARY})
target_include_directories(example PRIVATE ${AVFORMAT_INCLUDE_DIRS})

main.cpp:

#include <libavformat/avformat.h>

#include <stdio.h>


int main(int argc, char **argv) {
    if (argc < 2) {
        printf("example <input_file>");
        exit(EXIT_FAILURE);
    }

    AVFormatContext *pFormatContext = avformat_alloc_context();

    avformat_open_input(&pFormatContext, argv[1], nullptr, nullptr);
    printf("Format %s, duration %lld us", pFormatContext->iformat->long_name, pFormatContext->duration);


    avformat_free_context(pFormatContext);
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source