gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:23:49 26 4
gpt4 key购买 nike

我有一个预构建的目标文件(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是通过 Makefile( add_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 <...>)

最佳答案

只需删除导入:

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})

关于c++ - 将CMake构建的库链接到预构建的目标文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55374966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com