函数上的 C++ extern 关键字.为什么不只包含头文件? [英] C++ extern keyword on functions. Why no just include the header file?

查看:24
本文介绍了函数上的 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.

这篇关于函数上的 C++ extern 关键字.为什么不只包含头文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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