Unit VI: Preprocessor, Macro, Static and Shared Library
Mohsin F. Dar
Assistant Professor, Cloud & Software Operations Cluster
UPES
Four Stages of Transformation
Handling Directives and Text Manipulation
// Original code #include <stdio.h> #define MAX 100 int main() { int x = MAX; // Macro will be replaced return 0; }
Converting to Assembly Language
Creating Machine Code
Creating the Final Executable
Controlling the Compilation Process
| Command | Description |
|---|---|
| gcc -E file.c -o file.i | Preprocessing only |
| gcc -S file.c -o file.s | Compile to assembly |
| gcc -c file.c -o file.o | Compile to object file |
| gcc file.c -o program | Complete compilation to executable |
| gcc -Wall file.c | Enable all warnings |
| gcc -O2 file.c | Optimization level 2 |
Code Reusability and Modularity
Archive of Object Files
Step-by-Step Process
// mathops.h #ifndef MATHOPS_H #define MATHOPS_H int add(int a, int b); int multiply(int a, int b); #endif // mathops.c int add(int a, int b) { return a + b; } int multiply(int a, int b) { return a * b; }
r = insert/replace, c = create, s = create index
Linking with Your Program
// main.c #include <stdio.h> #include "mathops.h" int main() { int result1 = add(10, 20); int result2 = multiply(5, 6); printf("Addition: %d\n", result1); printf("Multiplication: %d\n", result2); return 0; }
-L. = Look for libraries in current directory
-lmathops = Link with libmathops.a (lib prefix and .a suffix are automatic)
Dynamic Linking at Runtime
Position Independent Code (PIC)
// mathops.h and mathops.c (same as before) int add(int a, int b) { return a + b; } int multiply(int a, int b) { return a * b; }
-fPIC = Position Independent Code (required for shared libraries)
-shared = Create a shared library
Dynamic Linking Process
-L. = Look in current directory for libraries
-lmathops = Link with libmathops.so
The dynamic linker needs to know where to find the shared library at runtime.
Choosing the Right Approach
| Feature | Static Libraries (.a) | Shared Libraries (.so) |
|---|---|---|
| Linking Time | At compile time | At runtime |
| Library Size | Larger executable (includes library code) | Smaller executable (shared code) |
| Updates | Requires recompilation to update library | Can update library without recompiling |
| Memory Usage | Each program has its own copy | Shared among programs |
| Performance | Faster (no runtime linking overhead) | Slight overhead at runtime |
Key Points from Lecture 25
Thank you for your attention!