Reading history

Create Your Own Static and Shared Library in C

7 min read 0 views

Build your own C library: write a header and source file, create a static .a and a shared .so library with gcc and ar, and link them into a program.

A library is a bundle of ready-made functions that many programs can use without copying the source code. You already use one every day: printf lives in the C standard library. In this lesson you will build your own small library twice, once as a static library and once as a shared one, and see exactly how the two differ.

In this lesson you will learn

  • Why programmers package code into libraries
  • The difference between static (.a) and shared (.so) libraries
  • How to write the header and source files for a library
  • The exact gcc and ar commands to build and link both kinds
  • How to fix the linker and loader errors you will meet

Why Package Code as a Library?

Suppose three of your programs need the same area calculations. You could paste the functions into each program, but then every bug fix has to be made three times. A library solves this:

  • Write once, reuse everywhere. Programs link to the library instead of carrying their own copy of the code.
  • Hide the details. Users see only the header file. The private parts stay inside the library.
  • Build faster. The library is compiled once. Programs that use it only need linking.
  • Share safely. You can give someone a compiled library and a header without giving away your source code.

Static vs Shared Libraries

Static libraryShared library
File name on Linuxlibname.alibname.so
When the code joins your programAt link time: it is copied into the executableAt run time: the program loads it when it starts
Executable sizeLargerSmaller
Needs the library file at run time?NoYes
Fixing a bug in the libraryRebuild every program that uses itReplace the .so file; programs pick up the fix next time they start
Windows equivalent.lib.dll

Static libraries are simple and self-contained, which suits small tools and embedded systems. Shared libraries save disk space and memory when many programs use the same code, which is why most system libraries on Linux are shared.

Building and Linking Both Kinds Step by Step

Step 1: Write the Header

The header is the library’s public face. It declares what users may call, and nothing more.

/* geom.h - public interface of a tiny geometry library */
#ifndef GEOM_H
#define GEOM_H

double circle_area(double radius);
double rect_area(double width, double height);
int    geom_calls(void);          /* how many area functions have run */

#endif

Step 2: Write the Source File

/* geom.c - the library's implementation */
#include "geom.h"

static int calls = 0;             /* private to the library */

double circle_area(double radius) {
    calls++;
    return 3.14159265358979 * radius * radius;
}

double rect_area(double width, double height) {
    calls++;
    return width * height;
}

int geom_calls(void) {
    return calls;
}

The counter calls is static, so programs using the library cannot touch it directly. They can only read it through geom_calls(). (See internal and external linkage for why this works.)

Step 3: Write a Program That Uses It

/* main.c - a program that uses the library */
#include <stdio.h>
#include "geom.h"

int main(void) {
    printf("circle r=2   : %.2f\n", circle_area(2.0));
    printf("rectangle 3x4: %.2f\n", rect_area(3.0, 4.0));
    printf("library calls: %d\n", geom_calls());
    return 0;
}

Step 4: Build and Run Both Versions

# Static library
gcc -c -Wall geom.c -o geom.o          # compile to an object file
ar rcs libgeom.a geom.o                # pack it into an archive
gcc main.c -L. -lgeom -o app_static    # link: -L = where, -l = which library
./app_static

# Shared library
gcc -c -fPIC -Wall geom.c -o geom_pic.o
gcc -shared geom_pic.o -o libgeom.so
gcc main.c -L. -lgeom -o app_shared
LD_LIBRARY_PATH=. ./app_shared         # tell the loader where to find libgeom.so
ar t libgeom.a                         # list what is inside the archive

Output

--- static build ---
circle r=2   : 12.57
rectangle 3x4: 12.00
library calls: 2
--- shared build ---
circle r=2   : 12.57
rectangle 3x4: 12.00
library calls: 2
--- inside libgeom.a ---
geom.o

Both programs print the same results. What each command does:

  • -c compiles without linking, producing an object file (.o).
  • ar rcs creates an archive: replace or add files, create it if needed, and write an index (s) so the linker can search it quickly.
  • -fPIC makes position-independent code, which can be loaded at any memory address. Shared libraries need it.
  • -L. adds the current folder to the library search path. -lgeom means “find libgeom.a or libgeom.so“. Leave out the lib prefix and the extension.

When both files exist, GCC prefers the shared one. Add -static to force static linking.

Linker and Path Errors

ErrorCauseFix
undefined reference to 'circle_area'The library was not linked, or it came before the file that uses itPut -lgeom after main.c on the command line
cannot find -lgeomThe linker does not know which folder holds the libraryAdd -L/path/to/folder
error while loading shared libraries: libgeom.soThe program built fine, but the loader cannot find the .so at run timeSet LD_LIBRARY_PATH, install the library in a system folder and run ldconfig, or link with -Wl,-rpath,/path
relocation ... recompile with -fPICObject files for a shared library were compiled without -fPICRecompile them with -fPIC
multiple definition of ...A function or variable is defined in the header, so every file that includes it gets a copyKeep only declarations in headers

Order matters because the linker reads left to right. It only pulls a function out of an archive if an earlier file has already asked for it. That is why gcc -lgeom main.c fails while gcc main.c -lgeom works.

Library Building Checklist

  1. Put only declarations, types and constants in the header, wrapped in an include guard.
  2. Make helper functions and internal variables static.
  3. Include your own header in the library’s source file, so the compiler checks that declarations and definitions match.
  4. Compile with -Wall -Wextra, and add -fPIC for shared libraries.
  5. Name the file libname.a or libname.so and link with -lname.
  6. Place -l options after the files that use them.
  7. Ship the header together with the library file.

Practice Exercises

Exercise 1. Add a function double triangle_area(double base, double height) to the library. Which files must change?

Show answer

Declare it in geom.h, define it in geom.c, then rebuild the library. For the static version, every program that wants it must be relinked. For the shared version, rebuilding libgeom.so is enough for programs that do not call the new function.

Exercise 2. The command gcc -L. -lgeom main.c -o app fails with “undefined reference”. Why?

Show answer

The library is listed before main.c. When the linker reads -lgeom, nothing needs its functions yet, so it takes nothing. Move -lgeom to the end.

Exercise 3. You delete libgeom.so. Which of the two programs still runs?

Show answer

app_static still runs, because the library code was copied into it. app_shared fails at start-up because the loader cannot find the library.

Frequently Asked Questions

Is a header file a library?

No. The header only declares the functions. The compiled code lives in the .a or .so file. You need both: the header for compiling, the library file for linking.

How do I see which shared libraries a program uses?

Run ldd ./app_shared on Linux. It lists each shared library and where the loader found it.

Can a static library contain several object files?

Yes. List them all: ar rcs libtools.a a.o b.o c.o. The linker copies only the object files your program actually needs.

Which should I choose for a beginner project?

Start with a static library. It has fewer moving parts and no run-time path problems.

Summary

  • A library packages reusable functions behind a header file.
  • Static libraries (.a) are copied into the program at link time; shared libraries (.so) are loaded at run time.
  • Build a static library with gcc -c and ar rcs; build a shared one with -fPIC and -shared.
  • Link with -L for the folder and -l for the name, placed after your source files.
  • “Cannot open shared object file” is a run-time path problem, not a build problem.
Lessons are also marked complete when you click Next.