如何将库链接到cmake中的可执行文件?
问题描述:
我有我的CMakeList.txt中的2个库和1个可执行文件。我希望链接到可执行文件的所有内容。如何将库链接到cmake中的可执行文件?
cmake_minimum_required(VERSION 2.8)
# Mark the language as C so that CMake doesn't try to test the C++
# cross-compiler's ability to compile a simple program because that will fail
project(jsos C ASM)
set(CMAKE_EXECUTABLE_OUTPUT_PATH "./build/")
# We had to adjust the CMAKE_C_FLAGS variable in the toolchain file to make sure
# the compiler would work with CMake's simple program compilation test. So unset
# it explicitly before re-setting it correctly for our system
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -nostartfiles")
# Set the linker flags so that we use our "custom" linker script
set(CMAKE_EXE_LINKER_FLAGS "-Wl,-T,${PROJECT_SOURCE_DIR}/etc/linker.ld")
add_library(duktape STATIC
src/libs/duktape/duktape.c
)
add_library(fdlibm STATIC
src/libs/fdlibm/e_acos.c
src/libs/fdlibm/e_acosh.c
src/libs/fdlibm/e_asin.c
MORE FILES
)
add_executable(kernel
src/start.S
src/kernel.c
src/cstartup.c
src/cstubs.c
src/rpi-gpio.c
src/rpi-interrupts.c
src/rpi-armtimer.c
src/rpi-systimer.c
)
add_dependencies(kernel fdlibm duktape)
target_link_libraries(kernel fdlibm duktape)
add_custom_command(
TARGET kernel POST_BUILD
COMMAND ${CMAKE_OBJCOPY} ./kernel${CMAKE_EXECUTABLE_SUFFIX} -O binary ./kernel.img
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
COMMENT "Convert the ELF output file to a binary image"
)
在那一刻,我链接这些我一起得到像一堆错误:
[100%] Linking C executable kernel
libduktape.a(duktape.c.obj): In function `duk_double_trunc_towards_zero':
src/libs/duktape/duktape.c:12102: undefined reference to `fabs'
src/libs/duktape/duktape.c:12102: undefined reference to `floor'
但fabs
和floor
是fdlibm
。 duk_double_trunc_towards_zero
在duktape
库中,因此似乎链接OK。我究竟做错了什么?
答
在你的声明:
target_link_libraries(kernel fdlibm duktape)
要解决从提供库的有序列表中搜索(fdlibm duktape
在这种情况下)这样的外部referece符号:
- 从开始图书馆被链接;
- 在它右侧的库上搜索符号;
在你的情况,解决的duktape
外部符号(其中一些是fdlibm
)时,fdlibm
甚至没有用于该搜索,并duktape
需要的符号都没有发现。只需在之后放置fdlibm ,duktape将让符号被找到。
例如,如果您取决于duktape
定义的一些符号,而且周围的其他方法有一个fdlibm
,你应该使用:
target_link_libraries(kernel fdlibm duktape fdlibm)
使符号总是解决。
尝试在'target_link_libraries'调用中交换库的顺序。 – arrowd
@arrowd作出回答,以便接受它。这是对的 – Justin808