本文介绍了如何做一个C / C ++编译器发现在头文件中的原型的定义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我宣布在头文件中的函数,并把该函数的定义,在其他一些文件,请问编译器/链接找到的定义是什么?它系统地搜索在它的每个文件,还是有一个更好的解决方案?这已被窃听我过去几天,我一直无法找到一个解释吧。

When I declare a function in a header file, and put the definition of that function in some other file, how does the compiler/linker find the definition? Does it systematically search every file in its path for it, or is there a more elegant solution? This has been bugging me for the past few days, and I've been unable to find an explanation for it.

推荐答案

编译器不这样做,连接器一样。

The compiler doesn't do this, the linker does.

虽然编译器上的一个源文件工作的时间,当调用链接它通过了所有由编译器生成的目标文件的名称,以及用户希望在有链接的任何库。因此,连接体具有一组可能潜在包含​​的定义文件的完整知识,它仅需要在这些目标文件的符号表的样子。它并不需要做超出任何搜索

While the compiler works on one source file at a time, when the linker is invoked it is passed the names of all of the object files generated by the compiler, as well as any libraries that the user wishes to have linked in. Therefore, the linker has complete knowledge of the set of files that could potentially contain the definition, and it needs only to look in the symbol tables of those object files. It doesn't need to do any searching beyond that.

举例来说,假设你有foo.h中和foo.c的定义和实现功能富()和bar.h和bar.c定义和实施巴()。说通话让bar.c包括foo.h.有三个步骤来此编译:

For example, say you have foo.h and foo.c defining and implementing function foo(), and bar.h and bar.c defining and implementing bar(). Say bar calls foo so that bar.c includes foo.h. There are three steps to this compilation:

gcc -c foo.c
gcc -c bar.c
gcc foo.o bar.o -o program

第一行编译foo.c的,生产foo.o.第二编译bar.c,生产bar.o.在这一点上,在目标文件文件bar.o,是外部符号。第三行调用连接器,它连接起来foo.o的和文件bar.o到名为计划的执行。当连接器处理文件bar.o,它看到了解析的外部符号,因此它会在所有其他目标文件被链接的符号表(本例中仅有foo.o的),并找到在foo.o的,并完成连接。

The first line compiles foo.c, producing foo.o. The second compiles bar.c, producing bar.o. At this point, in the object file bar.o, foo is an external symbol. The third line invokes the linker, which links together foo.o and bar.o into an executable called "program". When the linker processes bar.o, it sees the unresolved external symbol foo and so it looks in the symbol table of all of the other object files being linked (in this case just foo.o) and finds foo in foo.o, and completes the link.

使用库,这是一个有点复杂,他们出现在命令行可以根据您的连接关系的顺序,但它通常是同样的原理。

With libraries this is a bit more complicated, and the order that they appear on the command line can matter depending on your linker, but it's generally the same principle.

这篇关于如何做一个C / C ++编译器发现在头文件中的原型的定义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:12