CMake:将ELF嵌入可执行文件 [英] CMake: Embed ELF into executable
问题描述
我有一个项目,需要访问特殊部分.
I have a project that needs access to an ELF file embedded into the executable in a special section.
我以前是手工制作Makefile的,只是有一个shell脚本,我在其中使用objcopy将要嵌入的目标复制到.o文件中,然后在可执行文件中链接到该文件.
I was handcrafting Makefiles before and simply had a shell script where I used objcopy to copy the target I wanted to embed into an .o file, then link to this file in the executable.
# Create a new section and copy the binary there ($1=input $2=output name)
objcopy --input-target binary --output-target elf64-x86-64 \
--binary-architecture i386 $1 $2.o
现在,我要摆脱自定义的Makefile,并使用CMake生成它们.但是,我看不到链接到此类文件的简便方法.我可以创建和添加此文件,但不能对其进行链接:
Now I want to get rid of the custom Makefiles and use CMake to generate them. However, I don't see an easy way to link to such a file. I am able to create and add this file, but not to link against it:
# Invoke script to package module as a library
add_custom_command(OUTPUT ${PACKAGED_FILE}
COMMAND ./package.sh ${MODULE_FILE} ${PACKAGED_FILE}
WORKING_DIRECTORY ${MODULE_DIR}
DEPENDS ${MODULE_FILE}
COMMENT packaging file into ELF object
VERBATIM
)
add_custom_target(${PACKAGED_NAME} ALL DEPENDS ${PACKAGED_FILE})
我尝试将其添加为:
target_link_libraries(binary ${PROJECT_BINARY_DIR}/${PACKAGED_FILE})
但是,这失败了,因为文件还不存在.会的,但是CMake不知道.将目标名称添加为链接库也无济于事,因为找不到它.将其添加为还依赖项也无济于事.有谁知道如何实现这一目标?
However, this fails because the file isn't there yet. It will be, but CMake doesn't know that. Adding the target name as a link library doesn't help either because it can't be found. Adding it as a also dependency doesn't help. Does anyone have an idea how this could be accomplished?
推荐答案
我们在项目中正在做类似的事情-CMakeLists.txt
的以下部分起到了作用:
We are doing a similar thing in our project - the following part of our CMakeLists.txt
does the trick:
set(PROJECT_EMBED_OBJ_FILES "")
set(PROJECT_EMBED_FILES "file1.elf" "file2.elf")
foreach(FILENAME ${PROJECT_EMBED_FILES})
get_filename_component(FILENAME_ONLY ${FILENAME} NAME)
get_filename_component(FILEPATH_ONLY ${FILENAME} PATH)
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${FILENAME_ONLY}.o
WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/${FILEPATH_ONLY}
COMMAND ${CMAKE_OBJCOPY}
ARGS -I binary -O elf64-x86-64 -B i386 ${FILENAME_ONLY} ${CMAKE_CURRENT_BINARY_DIR}/${FILENAME_ONLY}.o )
list(APPEND PROJECT_EMBED_OBJ_FILES ${CMAKE_CURRENT_BINARY_DIR}/${FILENAME_ONLY}.o)
message(STATUS "Objcopy'ing ${FILENAME}")
endforeach(FILENAME)
然后在对add_executable
的调用中:
add_executable(projectname ${PROJECT_SOURCES} ${PROJECT_EMBED_OBJ_FILES})
这篇关于CMake:将ELF嵌入可执行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!