dlopen
- C course
- Advanced
- Lesson 49/83
- 5 min
Learn to load dynamic libraries with dlopen.
What is dlopen?
dlopen is the POSIX call that loads a shared library (.so) at runtime. It is declared in <dlfcn.h>. You load a library with void *h = dlopen(path, flags); if the return is NULL, an error occurred.
If you pass NULL for path, you get a handle to the main program's symbols; this is convenient for tests. flags is either RTLD_LAZY (symbols resolved on first use) or RTLD_NOW (all resolved immediately). RTLD_LAZY gives a fast startup. When done, close the library with dlclose(h).
Loading the main program
The simplest pattern for tests: void *h = dlopen(NULL, RTLD_LAZY);. This gives a handle to the main program's symbols. It usually succeeds because the main program is already loaded.
To print the success state, you can use printf("loaded\n"). Then close with if (h) dlclose(h);. dlclose closes the handle and decrements the reference count. This pattern's output is deterministic; it is environment-independent. Checking dlclose success is also a good habit.
Practice Load a library
Get a handle to the main program with void *h = dlopen(NULL, RTLD_LAZY);. Print the state with printf("loaded\n");. Close with if (h) dlclose(h);.
Starter code
#include <stdio.h>
#include <dlfcn.h>
// Load library
// Print state
// Close
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <dlfcn.h>
int main(void) {
void *h = dlopen(NULL, RTLD_LAZY);
printf("loaded\n");
if (h) dlclose(h);
return 0;
}Expected output
loaded
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which flag resolves symbols on first use?
- RTLD_LAZY Correct answer
- RTLD_NOW
- RTLD_GLOBAL
- RTLD_LOCAL
Explanation: RTLD_LAZY resolves symbols on first use; startup is fast.
2 dlopen call
void *h = dlopen(NULL, ____);
void *h = dlopen(NULL, RTLD_LAZY);
Explanation: RTLD_LAZY does lazy resolution.
3 Match dlopen parts
| Term | Meaning |
|---|---|
dlopen |
Loads library |
RTLD_LAZY |
Lazy |
RTLD_NOW |
Immediate |
dlclose |
Closes |