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
- Generate position-independent object file:
gcc -c NumberUtils.c -o NumberUtils.o -fPIC
- Create shared library:
gcc -shared -o libNumUtils.so NumberUtils.o
- Make the library available:
Temporary method (session only):
export LD_LIBRARY_PATH=/path/to/library
Permanent methods:
- Add to
.bashrc:
echo 'export LD_LIBRARY_PATH=/path/to/library' >> ~/.bashrc
source ~/.bashrc
- Copy to system library directory:
sudo cp libNumUtils.so /usr/lib
- Update ldconfig:
echo '/path/to/library' | sudo tee -a /etc/ld.so.conf
sudo ldconfig
- 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