gcc link order
今天在编译一个程序的时候发现,gcc 链接库文件的时候存在顺序的问题;如果顺序指定不对,则链接可能失败。
有一个库名字是 libatf-c.so,如果我以下面的方式编译,则在链接时会失败:
$ cc -Wall -latf-c test2.c -o test2
/tmp/ccsnTsF6.o: In function `atfu_my_test_case_head':
test2.c:(.text+0x23): undefined reference to `atf_tc_set_md_var'
/tmp/ccsnTsF6.o: In function `atfu_my_test_case_body':
test2.c:(.text+0x4f): undefined reference to `atf_tc_fail_check'
test2.c:(.text+0x73): undefined reference to `atf_tc_fail_check'
test2.c:(.text+0x97): undefined reference to `atf_tc_fail_requirement'
/tmp/ccsnTsF6.o: In function `main':
test2.c:(.text+0xbc): undefined reference to `atf_tp_main'
/tmp/ccsnTsF6.o: In function `atfu_tp_add_tcs':
test2.c:(.text+0xd6): undefined reference to `atf_tp_get_config'
test2.c:(.text+0xe6): undefined reference to `atf_no_memory_error'
test2.c:(.text+0xfe): undefined reference to `atf_tc_init_pack'
test2.c:(.text+0x10e): undefined reference to `atf_utils_free_charpp'
test2.c:(.text+0x11a): undefined reference to `atf_is_error'
test2.c:(.text+0x135): undefined reference to `atf_tp_add_tc'
test2.c:(.text+0x145): undefined reference to `atf_is_error'
collect2: error: ld returned 1 exit status
错误信息里面提到的这些函数,都在libatf-c.so中有定义。
如果我将 -latf-c 放到最后,则可以成功编译:
$ cc -Wall test2.c -o test2 -latf-c
我查了一下gcc帮助文档,发现这是gcc 的link order(链接顺序)的问题。
-l library
Search the library named library when linking. (The second alter-native with the library as a separate argument is only for POSIX compliance and is not recommended.)
It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, "foo.o -lz bar.o" searches library "z" after file "foo.o" but before "bar.o". If "bar.o" refers to functions in "z", those functions may not be loaded.
一个解决办法是用libtool来做编译链接,libtool 将自动解决链接顺序的问题,不用人工干预,省时省力。
$ cc -c test2.c
$ libtool --tag=CC --mode=link cc -latf-c test2.o -o test2
libtool: link: cc test2.o -o test2 /usr/local/lib/libatf-c.so
阅读(1995) | 评论(0) | 转发(0) |