3

I am trying to create a precompiled header file for my shared library using GCC. After making the necessary configuration and trying to build, I got these warnings:

cc1plus: warning: ./PrecompiledHeaders.h.gch/.c++: created and used with different settings of -fpic [enabled by default]

After some time searching, I found this piece of code which seems to suggest that PCH doesn't work with shared code:

/* -fpic and -fpie also usually make a PCH invalid.  */
if (data[0] != flag_pic)
  return _("created and used with different settings of -fpic");
if (data[1] != flag_pie)
  return _("created and used with different settings of -fpie");
data += 2;

So I changed my library to a static library and the error disappeared and compilation time was reduced! So is it indeed not possible to have a PCH with shared library? If yes, is there any work around this?

Rafid
  • 18,991
  • 23
  • 72
  • 108

2 Answers2

3

The message and the code you posted doesn't suggest that PCH can't be used with shared code. It tells you that you can't use a PCH file compiled with -fpic when compiling code without -fpic, and vice-versa. Same for -fpie.

Depending on the architecture, -shared might imply -fpic or other such options.

You need to pre-compile your headers with the same options as you will compile the rest of your code. If you want to be able to use PCH for both static and dynamic builds, you'll need (at least) two different sets of pre-compiled headers.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • Thanks comment. Please see the answer I just added and let me know if you have any comment about it. – Rafid May 12 '13 at 17:40
  • `-fPIC` is the only option for x86_64 for shared objects. I'm not too familiar with the intricate details, but you'll find more info & links here: http://stackoverflow.com/questions/3961446/why-does-gcc-not-implicitly-supply-the-fpic-flag-when-compiling-static-librarie - that's why I said 'use the same options' rather than tell you exactly what flag you should add - the exact options depend on your architecture. – Mat May 12 '13 at 17:55
1

Mat's answer is correct, but it didn't fix my problem, because I already tried to add -fpic when compiling the PCH file and it didn't work. It turned out that I need the -fPIC flag instead of -fpic. I am not sure exactly why, but possibly because my PCH file is too big. Quoting GCC manual pages:

-fPIC: If supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table. This option makes a difference on the m68k, PowerPC and SPARC.

What confuses me as the last statement where they say this only makes difference on m68k, PowerPC, and SPARC, but my machine is Intel i7 (3rd generation)!

Rafid
  • 18,991
  • 23
  • 72
  • 108