静态链接中目标文件和库的排序 [英] Ordering of object files and libraries in static linking

查看:73
本文介绍了静态链接中目标文件和库的排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用AR工具从简单的addv.omulto.o创建了一个简单的静态库libvec.a.目标文件addv.o包含1个功能符号(addvec),而multo.o包含1个功能(multvec).我还编写了一个简单的程序对其进行测试(driver.c,它添加了2个向量并使用了库中的addvec函数;它还包含了定义函数原型的vector.h).然后我用

I've created a simple static library libvec.a with AR tool from simple addv.o and multo.o. The object file addv.o contains 1 function symbol (addvec) and multo.o contains 1 function (multvec). I have also written a simple program to test it (driver.c which adds 2 vectors and uses addvec function from the library; also it has included vector.h that defines the function prototypes). And then I compiled it with

gcc -static driver.o ./libvec.a

,一切顺利.但是起初我尝试用

and everything went okay. But at first I tried to compile it with

gcc -static ./libvec.a driver.o

我收到一个错误:

undefined reference to 'addvec'

我想知道为什么当我第一次指定库时出现错误?订购应该重要吗?

I'm wondering why I got an error when I specified the library first? Should the ordering matter?

推荐答案

始终在库,句点之前链接对象文件.至少直到您对发生的事情有了足够的了解,才不需要首先问这个问题.

Always link object files before libraries, period. At least until you know enough about what's going on not to need to ask the question in the first place.

问题在于链接程序正在扫描库,并且正在寻找main().它找不到它,因此它不会从库中提取任何内容.然后,它扫描driver.o,查找要查找的内容,但不查找libvec.a中的内容(由于它们不相关而已将其遗忘).因此,libvec.a中的函数是不令人满意的引用-并且链接失败.

The trouble is that the linker scans the library, and it is looking for main(). It doesn't find it, so it doesn't pull anything out of the library. Then it scans driver.o, finds what is looking for, but not the things that were in libvec.a (which it has forgotten about as they weren't relevant). So, the functions from libvec.a are unsatisfied references — and the linking fails.

请注意,与静态库或共享库链接时,库之前的目标文件"有效.

Note that 'object files before libraries' works when linking with static libraries or shared libraries.

这篇关于静态链接中目标文件和库的排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆