CMake 错误:INTERFACE_LIBRARY 目标只能包含 INTERFACE 属性。目标 "mylib" 的 SOURCES 属性不是 INTERFACE 类型。
CMake Error: INTERFACE_LIBRARY targets may only have INTERFACE properties. The SOURCES property of target "mylib" is not INTERFACE.
ID: cmake/interface-library-sources-property
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| CMake 3.10+ | active | — | — | — |
| CMake 3.20+ | active | — | — | — |
| CMake 3.28+ | active | — | — | — |
根因分析
INTERFACE 库目标被错误地通过 set_target_properties 或 add_library 赋予源文件参数,这是不允许的,因为 INTERFACE 库是仅头文件的,没有构建产物。
English
An INTERFACE library target was mistakenly given source files via set_target_properties or add_library with source arguments, which is not allowed because INTERFACE libraries are header-only and have no build artifacts.
官方文档
https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#interface-libraries解决方案
-
Remove source files from add_library call and use target_sources with INTERFACE scope if needed, or convert to a STATIC library if sources are required.
-
Define the target as an OBJECT library if you need to collect object files, then link with other targets.
-
Use target_include_directories with INTERFACE scope to propagate headers without sources.
无效尝试
常见但无效的做法:
-
Adding SOURCES property via set_property with INTERFACE scope
95% 失败
The SOURCES property is inherently non-INTERFACE; even setting it as INTERFACE fails because CMake rejects it for INTERFACE libraries.
-
Changing library type to STATIC and linking sources
70% 失败
This changes the library's purpose and may break header-only design, causing unnecessary compilation and link errors.
-
Ignoring the error and using add_library with sources anyway
100% 失败
CMake will abort the configuration; the build cannot proceed without fixing the target definition.