A Beginner’s Guide to Using gcc: Compilation Process, Static and Dynamic Library Creation
This article provides a step-by-step guide for Java programmers on using gcc, covering the preprocessing, compilation, assembly, and linking stages, and demonstrates how to create and use static and dynamic libraries in C with practical code examples.
As a Java developer who often forgets the basic usage of gcc , the author writes a concise tutorial to record the essential steps of compiling C programs and building static and dynamic libraries.
Compilation Process
Step 1: Preprocess – expands header files, replaces macro definitions, and removes false conditional compilation blocks. Command:
gcc -E hello.c -o hello.iStep 2: Compile – translates the preprocessed source into assembly language. Command:
gcc -S hello.i -o hello.sStep 3: Assemble – converts the assembly file into an ELF relocatable object file. Command:
gcc -c hello.s -o hello.oStep 4: Link – links the object file to produce an executable, either dynamically or statically.
# Dynamic linking
gcc hello.o -o hello
# Static linking
gcc hello.o -o hello -staticStatic Library Creation
Write a simple addition function in add.c :
#include
int add(int a, int b) {
return a + b;
}Compile it to an object file:
gcc -c add.c -o add.oCreate a static library:
ar rcs libadd.a add.oWrite a test program that calls add , compile and link with the static library:
gcc test.c -o test libadd.aRunning ./test prints the result 3 .
Dynamic Library Creation
Compile the source with position‑independent code:
gcc -c add.c -o add.o -fPICBuild a shared library:
gcc -shared -o libadd.so add.oAlternatively, a one‑step command:
gcc -fPIC -shared -o libadd.so add.cWrite the same test program, compile and link against the shared library:
gcc test.c -o test -ladd -L ./Running the executable initially fails because the dynamic loader cannot find libadd.so :
./test
error while loading shared libraries: libadd.so: cannot open shared object file: No such file or directoryCopy the library to a standard search path (e.g., /lib64 ) and run again:
cp libadd.so /lib64
./test
3Verify the linkage with ldd :
ldd test
linux-vdso.so.1 => (0x00007ffe0f597000)
libadd.so => /lib64/libadd.so (0x00007fa5ab29f000)
libc.so.6 => /lib64/libc.so.6 (0x00007fa5aaed1000)
/lib64/ld-linux-x86-64.so.2 (0x00007fa5ab4a1000)In summary, the article walks through the complete gcc workflow, from source code to executable, and shows how to package code into static and shared libraries, providing essential commands and example code for each step.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.