Coder Perfect

Using the gcc command line, create a.so file from a.c file.

Problem

I’m attempting to make a hello world project that uses Linux dynamic libraries (.so files). So, I’ve got a file called hello.c:

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

Using gcc from the command line, how do I make a.so file that exports hello()?

Asked by sashoalm

Solution #1

To make a shared library, use the -fPIC (position independent code) parameter while compiling your C code.

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

This will create an object file (.o), which you can then use to build a.so file:

gcc hello.o -shared -o libhello.so

EDIT: Here are some ideas from the comments:

You can use

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

to complete it in a single step Jonathan Leffler (Jonathan Leffler)

I also recommend adding -Wall to your gcc statements to get all warnings and -g to get debugging information. – Starynkevitch, Basile

Answered by dreamcrash

Post is based on https://stackoverflow.com/questions/14884126/build-so-file-from-c-file-using-gcc-command-line