C
Symbol resolution
Learn symbol resolution and linking.
What is symbol resolution?
Symbol resolution is the linker matching undefined symbol references to their definitions. A function call compute(x) is recorded by the compiler as an "undefined symbol"; the linker searches for the definition of compute.
Undefined symbols are marked as "undefined" in the object file's symbol table. The linker scans all object files and libraries; for each undefined symbol it finds a definition. If no definition is found, an undefined reference error is issued. This is the mechanism that lets functions and variables find each other in multi-file projects.
How the linker resolves
The linker performs symbol resolution in two passes. In the first pass, it scans all object files and lists the symbols each file provides and needs. In the second pass, for each needed symbol it searches for a definition.
If a symbol is defined in more than one file, a multiple definition error is issued. If it is not defined in any file, an undefined reference error is issued. Static libraries (.a) include only the needed objects; dynamic libraries (.so) are resolved at run time. This process is the core of C's separate compilation model.
Exercise Forward declaration and definition
Write the forward declaration int compute(int x); (symbol reference). In int main(void) call printf("Sonuç: %d\n", compute(21)). After main, write the definition int compute(int x) { return x * 2; } (symbol definition).
Show example solution
#include <stdio.h>
int compute(int x);
int main(void) {
printf("Sonuç: %d\n", compute(21));
return 0;
}
int compute(int x) {
return x * 2;
}
Test yourself
-
Complete the declaration keyword
____ int compute(int x);
Show answer
extern int compute(int x);
-
What happens if a symbol stays undefined?
- The compiler warns
- The program runs anyway
- It silently becomes zero
- The linker errors
Show answer
The linker errors — An undefined symbol causes the linker to issue 'undefined reference'.
-
Match symbol status
- Defined
- Provided
- Undefined
- Needed
- Multiple definition
- Duplicate error
- Not found
- Linker error
Next lesson: Relocation