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

CLinuxGccShared Libraries

C Problem Overview


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?

C Solutions


Solution 1 - C

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsashoalmView Question on Stackoverflow
Solution 1 - CdreamcrashView Answer on Stackoverflow