8

I'd like to build both static and shared libraries in a project.

I know that shared libraries need to be be created from objects compiled with -fpic to get Position Independent Code while the static library doesn't need this. This is all fine and I can create either a shared or static library.

I wouldn't want to compile my source twice to get the different object files, so how is this usually done? I read how to get a shared library based on a static one. However, the example shows the static library being built with -fpic. Is this the way to go? Are there things to be aware of with this?

Is there a common approach to compiling both static and shared libraries? E.g. first static and based on the lib a shared version is created?

I'm interested to know if there are different approaches for this and what to consider when selecting.

I'm using gcc4.4 on Linux.

Thanks in advance!

Community
  • 1
  • 1
murrekatt
  • 5,961
  • 5
  • 39
  • 63

1 Answers1

6

The common approach that I've seen is, in fact, compiling your source twice, once with PIC and once without. If you don't do that, you either wind up with PIC overhead in the static library, or a shared object that can't be relocated by the OS (effectively meaning it's NOT shared across multiple clients of the library).

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • For this approach, how would one arrange the object files if one wants to have both static and shared libraries built simultaneously? Something like obj/static/... and obj/shared/... ? – murrekatt Feb 01 '11 at 14:44
  • @murrekatt: Sure. It's nice to use a separate directory for each build configuration so you can use many simultaneously without completely recompiling to update each. Making those subdirs under one directory to hold them gives exactly what you show, at least if you use "obj" as your main build directory and "static" and "shared" the names of those two builds. – Fred Nurk Feb 01 '11 at 15:08