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

查看:182
本文介绍了函数的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天全站免登陆