C
Static and dynamic
Learn the difference between static and dynamic linking.
Static linking
Static linking embeds all library code into the executable. The linker pulls needed objects from .a (archive) files and includes them in one large executable.
The advantage is independence: the target machine need not have the library installed. The disadvantage is large file size and update difficulty: when the library is updated, the whole program must be re-linked. In C, the static keyword also provides internal linkage: a variable or function is visible only within its own file and cannot be used by other files.
Dynamic linking
Dynamic linking does not embed library code; instead, a reference to a .so (shared object) file is left in the executable. When the program runs, the loader loads the library into memory and resolves symbols.
The advantage is small file size and easy updates: when the library is updated, the program is not re-linked. The disadvantage is that the library must be installed on the target machine. The extern keyword provides external linkage: the symbol is visible to other files. Dynamic linking resolves these external symbols at run time.
Exercise Internal and external linkage
Define static int internal_counter = 5; (internal linkage). Define int external_counter = 10; (external linkage). Write int main(void) and print both with printf("Dahili: %d\n", internal_counter) and printf("Harici: %d\n", external_counter).
Show example solution
#include <stdio.h>
static int internal_counter = 5;
int external_counter = 10;
int main(void) {
printf("Dahili: %d\n", internal_counter);
printf("Harici: %d\n", external_counter);
return 0;
}
Test yourself
-
What does static linking produce?
- A shared library
- A source file
- Only a header file
- One large executable
Show answer
One large executable — Static linking embeds all code into one executable.
-
Complete the internal linkage keyword
____ int internal_counter = 5;
Show answer
static int internal_counter = 5;
-
Match linking type
- Static
- Code embedded
- Dynamic
- .so loaded
- static keyword
- Internal linkage
- extern keyword
- External linkage
Next lesson: ELF format