I was reading a textbook which describes static libraries anad shared libraries. There are two source files, addvec.c and multvec.c, to create a static library of them, we would use the ar tool as follows:

linux> gcc -c addvec.c multvec.c
linux> ar rcs libvector.a addvec.o multvec.o

so basically it just create relocatable object files (.o) first then use the ar tool with those .o files.

But if we want to build a shared library libvector.so then the command in the book is:

linux> gcc -shared -fpic -o libvector.so addvec.c multvec.c

note that we use source file (.c) as arguments directly, not relocatable object files.

So why for share libraries, there is no need to produce relocatable object files and use source files directly, which is inconsistent compared to static linking which uses relocatable object files?


1 Answer 1


You can build the component objects of a shared library separately:

gcc -fpic -c addvec.c multvec.c
gcc -shared -fpic -o libvector.so addvec.o multvec.o

Note however that all compilation and linking steps must use the same flags. I suspect this is the main reason behind the approach used in your textbook. The static library doesn’t need position-independent code, but the shared library does. Instead of explicitly building the individual object files twice, or “wasting” PIC on the static library, the shared library is built using PIC from the source files.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .