多个已定义符号的C/C ++链接器顺序 [英] C/C++ linker order for multiple defined symbols

查看:105
本文介绍了多个已定义符号的C/C ++链接器顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在目标文件和库中定义了相同的符号,则GNU链接程序将从目标文件中获取该符号.考虑以下示例:

g++ -L"dir/to/lib" -o Executable Test.o foo.o -lMyLib

如果我在foo.cpp和源文件"MyLib"中都定义了具有相同签名的函数foo,则如果我使用此顺序,GNU链接器总是更喜欢前一个. /p>

此行为GNU工具链是否特定?您是否从其他行为相同的链接器中知道呢?是否在任何地方都有文档记录(GNU文档,C ++标准)?我什么都找不到...

我想在进行单元测试(也称为链接缝)时使用此功能替换/模拟某些功能.

解决方案

也许.

链接程序实际上如何处理给定的文件,具体取决于 链接器,但就您所描述的确切情况而言,我认为不会 任何变化.指定对象文件时,会包含 进入最终版本,您将获得它定义的所有符号; 如果两个目标文件定义了相同的符号,则通常会得到一个 来自链接器的错误(但由于符号较弱或 类似于Fortran的数据定义处理).图书馆是馆藏 目标文件;库的标准处理是链接器 扫描它,并合并任何对象(并且仅包含那些对象) 定义一个否则未定义的外部.如果目标文件在 库仅定义相关符号,并且其定义具有 已由明确指定的目标文件(链接器)解析 不会将库中的目标文件合并到程序中. 但是,如果库中的目标文件也定义了其他符号, 其中之一解决了否则无法定义的外部对象 库中的文件将与 它定义的所有符号.这可能导致多重 定义.

If I have the same symbol defined in an object file and in a library the GNU linker takes the symbol from the object file. Consider this example:

g++ -L"dir/to/lib" -o Executable Test.o foo.o -lMyLib

If I have defined a function foo with the same signature in both foo.cpp and in a source file "MyLib" was compiled from, the GNU linker always prefers the one from the former if I use this order.

Is this behaviour GNU toolchain specific? Do you know from other linkers that behave the same way? Is this anywhere documented (GNU documentation, C++ standard)? I couldn't find anything...

I would like to use this feature to replace/mock certain functions while doing unit testing (aka link seam).

解决方案

Maybe.

Exactly how the linker processes the files it was given depends on the linker, but in the exact case you've described, I don't think there will be any variation. When you specify an object file, it is included into your final build, and you will get any symbols it defines from it; if two object files define the same symbol, you will normally get an error from the linker (but there are exceptions, due to weak symbols or Fortran-like handling of data definitions). A library is a collection of object files; the standard handling of a library is for the linker to scan it, and incorporate any objects (and only those objects) which define an otherwise undefined external. If the object file in the library only defines the symbol in question, and its definition has already been resolved by an explicitly specified object file, the linker will not incorporate the object file from the library into the program. If the object file in the library also defines other symbols, however, and one of those resolves an otherwise undefined external, the object file from the library will be incorporated into your program, along with all of the symbols it defines. Which could lead to multiple definitions.

这篇关于多个已定义符号的C/C ++链接器顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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