简体   繁体   English

C ++编译器是否会优化未使用的#include?

[英]Does C++ compiler optimize out #includes that are not used?

When building a growing library of classes/functions, I've commonly seen a sort of "umbrella" header file that #includes all the common header files of a project. 在构建不断增长的类/函数库时,我通常会看到一种“伞”头文件,其中包含项目的所有常见头文件。 For example: 例如:

dsp.h
#include "file1.h"
#include "file2.h"
...
#include "filex.h"

Sometimes I might need everything, but other times maybe only a selection of features/options. 有时我可能需要所有东西,但其他时候可能只选择了一些功能/选项。 If #include dsp.h, but don't use anything from file2.h for example, does the compiler know? 例如,如果#include dsp.h但不使用file2.h中的任何内容,则编译器知道吗? Is it possible for it to optimize it out in the build? 是否有可能在构建中对其进行优化?

Otherwise, my solution is to wrap optional code inside preprocessor directives and then define what I need. 否则,我的解决方案是将可选代码包装在预处理器指令中,然后定义我需要的代码。 Perhaps this is a safer, more efficient solution? 也许这是一个更安全,更有效的解决方案?

Are you talking about code optimization or optimization of build time? 您是在谈论代码优化还是构建时间优化?

Unnecessary, unused headers will not change the code that is being generated, so there is no question of optimization here. 不必要的,未使用的标头不会更改正在生成的代码,因此这里没有优化的问题。

However, it will increase build time. 但是,这将增加构建时间。 This is not optimized by build tools. 生成工具未对此进行优化。 If you are looking to optimize build time, look at the book Large Scale C++ Software Design by John Lakos . 如果您想优化构建时间,请参阅John Lakos撰写的《 大规模C ++软件设计 》一书。

The preprocessor doesn't do any optimization. 预处理器不做任何优化。 It doesn't know anything about the semantics of your code and thus cannot tell whether you're using anything from a header file or not. 它对代码的语义一无所知,因此无法判断是否正在使用头文件中的任何内容。 So no, #include statements are not optimized out. 因此,不, #include语句未进行优化。

Since the preprocessor is a separate program (and language) from the C++ compiler, there's no way for the preprocessor to know what is used. 由于预处理器是与C ++编译器分开的程序(和语言),因此预处理器无法知道使用了什么。 So the compiler will receive everything that was in the header file. 因此,编译器将接收头文件中的所有内容。

The include files are are read, and are inserted part of the source code before the compiler really starts generating code. 在编译器真正开始生成代码之前,将读取包含文件并将它们插入源代码的一部分。

Yes. 是。 As a general rule, things that are not referenced by the program are not put into the final executable. 通常,程序未引用的内容不会放入最终的可执行文件中。 It is ok to think of that as being an optimization. 可以认为这是一种优化。 The details will differ depending on the compiler and linker. 详细信息将取决于编译器和链接器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM