将CMake构建的库链接到预构建的目标文件

时间:2019-03-27 10:27:27

标签: c++ build cmake linker

我具有以下设置,其中包含一个预先构建的目标文件(payload.o)和4个库lib1lib2lib3lib4 cmake项目。

prebuilt/
--- payload.o
lib1/
--- CMakeLists.txt
--- src/
--- ...
lib2/
--- CMakeLists.txt
--- src/
lib34/
--- Makefile
--- src1/
--- src2/

payload.o是已提供的预构建对象,不能在此cmake项目中构建。

lib1lib2cmake感知的库,并且lib3lib4是通过Makefileadd_custom_command())生成的

lib2取决于lib1个符号,lib3取决于lib2lib1取决于lib3,此外lib4取决于在lib3上。如您所见,它是一个循环依赖图。

此外,payload.o同时取决于lib3lib4


因此,我试图实现的链接器调用是:

ld prebuilt/payload.o -L <cmake build directory here> --start-group lib1 lib2 lib3 --end-group lib4

我尝试通过以下方式添加预构建的目标文件:

add_executable(payload IMPORTED prebuilt/payload.o)
target_link_libraries(payload lib1 lib2 lib3 lib4)

但这失败并显示错误消息

Cannot specify link libraries for target "payload" which is not built by this project

有什么想法吗?


所讨论的cmake缩写文件:

project(...)
# build lib1/lib2
add_subdirectory(lib1)
add_subdirectory(lib2)


# add custom command & target
add_custom_command(
    OUTPUT
    "${LIB3} ${LIB4}"
    COMMAND
...
    VERBATIM
    )
add_custom_target(lib34 DEPENDS "${LIB3} ${LIB4}")
add_dependencies(lib34 lib2)

add_library(lib3 STATIC IMPORTED ${LIB3})
add_dependencies(lib3 lib34)
add_library(lib4 STATIC IMPORTED ${LIB4})
add_dependencies(lib4 lib34)

# lib1 -> lib3
add_dependencies(lib1 lib3)

# payload target
add_executable(payload IMPORTED 
    prebuilt/payload.o
    )

add_dependencies(payload lib3 lib4)
target_link_libraries(payload lib1 lib2 lib3 lib4 <...>)

1 个答案:

答案 0 :(得分:0)

只需删除导入的内容:

add_executable(payload prebuilt/payload.o)

cmake应该知道该怎么做。 IMPORTED用于cmake之外的可执行构建。

或者,您可以指定导入的对象库,因为这正是您所拥有的-由外部实体构建的对象文件:

# import .o file as object library
add_library(payload_object OBJECT IMPORTED GLOBAL)
set_target_properties(payload_object IMPORTED_OBJECTS ${CMAKE_CURRENT_SOURCE_DIR}/prebuilt/payload.o

# create payload executable, add payload objects
add_executable(payload ${TARGET_OBJECTS:payload_object})