Rafid
Rafid

Reputation: 20189

Precompiled header file for shared library project using GCC

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?

Upvotes: 3

Views: 2408

Answers (2)

Rafid
Rafid

Reputation: 20189

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)!

Upvotes: 1

Mat
Mat

Reputation: 206689

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.

Upvotes: 3

Related Questions