Implementing Modular C Programming with Dynamic Libraries

Modular C Programming

C programs typically separtae decalrations into .h header files, implementations into .c source files, and main logic into main.c.

Consider a function that returns the maximum of two numbers:

main.c

#include <stdio.h>
#include "NumberUtils.h"

int main() {
    int x = 42, y = 17;
    printf("Max of %d and %d is %d\n", x, y, findMax(x, y));
    return 0;
}

NumberUtils.h

#ifndef NUMBER_UTILS_H
#define NUMBER_UTILS_H

int findMax(int num1, int num2);

#endif

NumberUtils.c

int findMax(int num1, int num2) {
    return (num1 > num2) ? num1 : num2;
}

Creating Dynamic Libraries

  1. Generate position-independent object file:
gcc -c NumberUtils.c -o NumberUtils.o -fPIC
  1. Create shared library:
gcc -shared -o libNumUtils.so NumberUtils.o
  1. Make the library available:

Temporary method (session only):

export LD_LIBRARY_PATH=/path/to/library

Permanent methods:

  1. Add to .bashrc:
echo 'export LD_LIBRARY_PATH=/path/to/library' >> ~/.bashrc
source ~/.bashrc
  1. Copy to system library directory:
sudo cp libNumUtils.so /usr/lib
  1. Update ldconfig:
echo '/path/to/library' | sudo tee -a /etc/ld.so.conf
sudo ldconfig
  1. Compile with library:
gcc main.c -o main -lNumUtils -L./lib -I./include

Makefile Example

SRC = $(wildcard *.c)
OBJ = $(patsubst %.c,%.o,$(SRC))

all: program

program: main.c
	gcc main.c -o program -lNumUtils -L./lib -I./include

libNumUtils.so: NumberUtils.o
	gcc -shared -o libNumUtils.so NumberUtils.o

NumberUtils.o: NumberUtils.c
	gcc -c NumberUtils.c -o NumberUtils.o -fPIC

clean:
	-rm -f $(OBJ) program

To safely clean:

make clean -n  # Dry run
make clean     # Actual cleanup

Tags: c programming modular programming Dynamic Libraries Makefile

Posted on Fri, 31 Jul 2026 16:36:28 +0000 by aQ