2

I understand g++ -fPIC option as nicely explainjed in: GCC -fPIC option I have many source files those are managed through makefile for build. It's difficult to segregate source files that is meant for being part of an executable or shared library. Can I used -fPIC option of g++ for any file that goes under compilation as:

g++ -c -fPIC ....

and later, if it is a shared library, link with -shared, otherwise without -shared for executable.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69

2 Answers2

2

It is possible to build executables with -fPIC but this may result in performance penalties as compiler will make more conservative assumptions e.g. about inlining (to allow runtime symbol interposition). To produce position-independent executable, you'd better off using -fPIE flag (most modern distros e.g. Ubuntu build with it on by default now).

In any case, unless you really don't care about performance you'll need to compile your files twice, with different flags.

yugr
  • 19,769
  • 3
  • 51
  • 96
-1

Can I used -fPIC option of g++ for any file that goes under compilation?

Yes. If something such as an assembly file is given, it'll just have no effect.

[ ... ] and later, if it is a shared library, link with -shared?

Yes.

OMGtechy
  • 7,935
  • 8
  • 48
  • 83
  • This answer does not mention potential consequences of using `-fPIC` (e.g. performance issues). – yugr Mar 24 '17 at 15:27