Why use precompiled headers (C/C++)?

后端 未结 5 428
傲寒
傲寒 2020-12-01 01:00

Why use precompiled headers?


Reading the responses, I suspect what I\'ve been doing with them is kind of stupid:

#pragma once

// Defines used         


        
相关标签:
5条回答
  • 2020-12-01 01:06

    So you don't have to compile them every time you build your project. They're used for system headers that aren't going to change.

    0 讨论(0)
  • 2020-12-01 01:08

    In C/C++, the #include mechanism is a textual copy of the file specified into the current file. Headers include other headers (which include yet other headers), so when you do a #include, it could be adding tens of thousands of lines of C++ into each cpp file (or cxx, c, whatever), all of which need to be compiled each time. This can be a sever bottleneck for large projects.

    Precompiled headers speed this up by compiling each header once, then including that compiled state into the cpp they are included in.

    0 讨论(0)
  • 2020-12-01 01:09

    It compiles a lot quicker. C++ compilation takes years without them. Try comparing some time in a large project!

    0 讨论(0)
  • 2020-12-01 01:18

    Re: your current usage, if you have a target with a very large number of files, it may still be faster to use PCH in that way - try switching them off to find out. It depends: if you have a lot of headers of your own, and you change them only infrequently, and you have a very large number of source files that you change much more frequently, then your PCH usage will cut rebuild times.

    But normal advice is to only put things in PCH that never change, because there is a certain overhead to producing the PCH itself. If you trigger that off with every rebuild (by constantly tweaking one of your headers), using PCH may make the rebuild slower.

    0 讨论(0)
  • 2020-12-01 01:32

    It speeds up compilation.

    When you're including headers from other projects, you don't expect to change them. If you put these into a precompiled header, then that code will not have to be recompiled when you make changes to your source code. This reduces repetitive compilation of unchanged code, speeding up compile time.

    0 讨论(0)
提交回复
热议问题