Build .so file from .c file using gcc command line

sashoalm picture sashoalm · Feb 14, 2013 · Viewed 171.9k times · Source

I'm trying to create a hello world project for Linux dynamic libraries (.so files). So I have a file hello.c:

#include <stdio.h>
void hello()
{
    printf("Hello world!\n");
}

How do I create a .so file that exports hello(), using gcc from the command line?

Answer

dreamcrash picture dreamcrash · Feb 14, 2013

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

gcc -c -fPIC hello.c -o hello.o

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

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch