7

I recently found out about precompiled headers in C++, specifically for gcc compilers. I did find something about the .h.gch files on the net, but haven't yet been able to use them.

I need to know:

  1. How to create a .h.gch file? My code isn't creating one?
  2. Once created, how to use it? do you include it like any other user-defined file? ex: #include "SomeCode.h.gch"

Or is there some other way of using it? please help

zhirzh
  • 3,273
  • 3
  • 25
  • 30

1 Answers1

9

Using GCH (Gnu preCompiled Headers) is easy, at least in theory.

How to create a GCH

Just use gcc <compiler-options> myfile.h. That will create myfile.h.gch. You can use the -o <name> to specify the name of the output file.

If your header file is C++, you will have to name it myfile.hpp or myfile.hh, or GCC will try to compile it as C and probably fail. Alternatively you can use the -x c++-header compiler option.

How to use a GCH

Put your myfile.h.gch in the same directory than myfile.h. Then it will be used automatically instead of myfile.h, at least as long as the compiler options are the same.

If you do not want to (or can) to put your *.gch in the same directory of your *.h, you can move them to a directory, say ./gch, and add the option -Igch to your compiler command.

How to know your GCH is being used

Use gcc -H <compiler-options> myfile.c. That will list the included files. If your myfile.h.gch does not appear, or has an x, then something is wrong. If it appears with a !, congratulations! You are using it.

rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • i tried the `gcc -H` option but instead of `gcc`, I used `g++` and an infinite loop of some sort began anyways, i did get my `.h.gch` file, just dont yet know if it is being used – zhirzh May 30 '14 at 21:21
  • The only result in google about "-Igch" is your comment. Where did you get this from? – Maciej Załucki Apr 01 '22 at 04:48
  • @MaciejZałucki: You are reading it as an option called `Igck`, but it is actually an option `I` plus an argument `gch`: `-I` is the well-known switch to add a directory to the header search list; and `gch` is just the name of the directory I made up `./gch`. – rodrigo Apr 01 '22 at 13:19
  • The way you wrote it is a bit misleading then :) I figured it out, GCC looks for precompiled headers the same way it is looking for headers - first match from include directories is used. One thing I have to check is if it is first looking for .h.gch everywhere and then for .h, or it is looking for .h.gch then .h in each include dir. I suspect it's latter so the ```-I /gch/dir``` needs to be included before the header itself. – Maciej Załucki Apr 02 '22 at 00:43