Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get .so file once we compile a c program? [duplicate]

Tags:

c

gcc

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.

like image 768
user3133828 Avatar asked Feb 14 '23 07:02

user3133828


2 Answers

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
like image 105
SuRu Avatar answered Feb 23 '23 10:02

SuRu


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
like image 41
Jack Avatar answered Feb 23 '23 09:02

Jack