4

How can I generate a shared library (.so) file from compilation of C program. I meant to say if i compile a C program i'll get a.out. Instead of that how i can get .so file.

Jack
  • 131,802
  • 30
  • 241
  • 343

2 Answers2

4

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC file.c -o file.o

This will generate an object file (.o), now you take it and create the .so file:

gcc file.o -shared -o lib_file.so
SuRu
  • 739
  • 1
  • 6
  • 19
4

To generate a shared library first you must create the normal binary .o files by specifying the -fPIC flag to obtain position independent code. This is necessary because every jump or call inside the library will have relative offset and will be available to relocation when the library is loaded into memory to be used by a process (read: less optimization but availability to be used at any address)

Then you use gcc again by specifying that you want to create the library from the object files:

gcc -shared -o library_name.so a.o b.o
Jack
  • 131,802
  • 30
  • 241
  • 343