cmake type_error ai_generated true

CMake Error: Target 'mylib' has INTERFACE_LIBRARY type but target_link_libraries was called with non-INTERFACE keyword

ID: cmake/target-links-interface-libraries-with-non-interface-keyword

Also available as: JSON · Markdown · 中文
95%Fix Rate
90%Confidence
1Evidence
2024-01-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
CMake 3.20 active
CMake 3.22 active
CMake 3.28 active

Root Cause

A target defined as INTERFACE (header-only) library must only use INTERFACE keyword in target_link_libraries, but PRIVATE or PUBLIC was used.

generic

中文

定义为INTERFACE(仅头文件)库的目标必须在target_link_libraries中仅使用INTERFACE关键字,但使用了PRIVATE或PUBLIC。

Official Documentation

https://cmake.org/cmake/help/latest/command/add_library.html#interface-libraries

Workarounds

  1. 100% success Replace PUBLIC with INTERFACE in target_link_libraries for the INTERFACE library
    Replace PUBLIC with INTERFACE in target_link_libraries for the INTERFACE library
  2. 80% success Convert the INTERFACE library to a STATIC library with a dummy source file if link dependencies are needed
    Convert the INTERFACE library to a STATIC library with a dummy source file if link dependencies are needed
  3. 70% success Use target_link_options instead of target_link_libraries for compiler-specific flags
    Use target_link_options instead of target_link_libraries for compiler-specific flags

中文步骤

  1. Replace PUBLIC with INTERFACE in target_link_libraries for the INTERFACE library
  2. Convert the INTERFACE library to a STATIC library with a dummy source file if link dependencies are needed
  3. Use target_link_options instead of target_link_libraries for compiler-specific flags

Dead Ends

Common approaches that don't work:

  1. Change the target type to STATIC or SHARED 50% fail

    Changing target type may break the build if the library is meant to be header-only.

  2. Use PUBLIC keyword but add dummy source files 90% fail

    PUBLIC is still not allowed for INTERFACE libraries; only INTERFACE keyword is valid.

  3. Remove all target_link_libraries calls 30% fail

    This may lose necessary link dependencies for consumers of the header-only library.