C ++头文件如何工作? [英] How do C++ header files work?

查看:181
本文介绍了C ++头文件如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在C ++程序中包含头文件中的某些函数时,整个头文件代码是否被复制到最终的可执行文件,或者只生成特定函数的机器代码。例如,如果我从C ++中的< algorithm> 头调用 std :: sort 只为sort()函数或整个< algorithm> 头文件生成。

When I include some function from a header file in a C++ program, does the entire header file code get copied to the final executable or only the machine code for the specific function is generated. For example, if I call std::sort from the <algorithm> header in C++, is the machine code generated only for the sort() function or for the entire <algorithm> header file.

我认为类似的问题存在于Stack Overflow的某个地方,但我已尽力找到它(我曾经看过一次,但失去了链接)。如果你能指出我,那将是美好的。

I think that a similar question exists somewhere on Stack Overflow, but I have tried my best to find it (I glanced over it once, but lost the link). If you can point me to that, it would be wonderful.

推荐答案

这里有两个不同的问题:

You're mixing two distinct issues here:


  1. 由预处理程序处理的头文件

  2. 由C ++链接器选择性链接代码



头文件



这些只是简单地由预处理器复制到 include 。当 #include< code>时,将算法的所有代码复制到 .cpp algorithm>

Header files

These are simply copied verbatim by the preprocessor into the place that includes them. All the code of algorithm is copied into the .cpp file when you #include <algorithm>.

大多数现代链接器不会链接到在应用程序中未调用的函数。也就是说写一个函数 foo ,从不调用它 - 它的代码不会进入可执行文件。所以如果你 #include< algorithm> 并且只使用 sort ,会发生什么:

Most modern linkers won't link in functions that aren't getting called in your application. I.e. write a function foo and never call it - its code won't get into the executable. So if you #include <algorithm> and only use sort here's what happens:


  • 预处理器将整个算法文件放到源文件中

  • 您只调用 sort

  • 链接分析这个并且只添加 sort (和它调用的函数,如果有的话)。其他算法的代码未添加

  • The preprocessor shoves the whole algorithm file into your source file
  • You call only sort
  • The linked analyzes this and only adds the source of sort (and functions it calls, if any) to the executable. The other algorithms' code isn't getting added

也就是说,C ++模板会使问题复杂化。这是一个复杂的问题,在这里解释,但简而言之 - 模板由编译器扩展你实际使用的所有类型。因此,如果有向量 int 向量 string ,编译器将为您的代码中的向量类生成两个副本。因为你使用它(否则编译器不会生成它),链接器也将它放入可执行文件。

That said, C++ templates complicate the matter a bit further. It's a complex issue to explain here, but in a nutshell - templates get expanded by the compiler for all the types that you're actually using. So if have a vector of int and a vector of string, the compiler will generate two copies of the whole code for the vector class in your code. Since you are using it (otherwise the compiler wouldn't generate it), the linker also places it into the executable.

这篇关于C ++头文件如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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