函数上的 C++ extern 关键字.为什么不只包含头文件?

2022-01-11 00:00:00 linker c++ extern

如果我理解正确,这意味着

If I understand it correctly this means

extern void foo();

函数 foo 是在另一个翻译单元中声明的.

that the function foo is declared in another translation unit.

1) 为什么不直接#include 声明该函数的标头?

1) Why not just #include the header in which this function is declared?

2) 链接器如何知道在链接时到哪里寻找函数?

2) How does the linker know where to look for function at linking time?

也许我应该澄清一下,上面的声明之后是使用函数

edit: Maybe I should clarify that the above declaration is then followed by using the function

foo();

在这个翻译单元中从未定义过.

It is never defined in this translation unit.

推荐答案

1) 可能没有头文件.但是是的,一般来说,对于大型项目,如果多个翻译单元要使用该功能,您应该有一个头文件(不要重复自己).

1) It may not have a header file. But yes, in general, for large projects, you should have a header file if multiple translation units are going to use that function (don't repeat yourself).

2) 链接器搜索它被告知要查找函数和其他符号的所有目标文件和库.

2) The linker searches through all the object files and libraries it was told about to find functions and other symbols.

相关文章