C++ extern keyword on functions. Why no just include the header file?(函数上的 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 关键字.为什么不只包含头文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:函数上的 C++ extern 关键字.为什么不只包含头文件?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
