C Reference ยท POSIX and Systems
C dlopen() function
Reference for dlopen(), dlsym(), dlclose() and dlerror(): load shared libraries at run time, look up functions by name, build a plugin system and handle errors.
dlopen() loads a shared library (a .so file on Linux, .dylib on macOS) while the program is running. dlsym() then looks up a function or variable in it by name, and dlclose() releases it. This is how plugin systems, language runtimes and optional features are built: the program decides at run time which code to load, instead of linking it at build time.
The functions are POSIX, declared in <dlfcn.h>. On older glibc versions you must link with -ldl; since glibc 2.34 they are in the main C library.
The examples on this page are read-only. Our online runner builds each program as a single file without -ldl, so dlopen programs do not link there. Compile them yourself with gcc plugin_demo.c -o plugin_demo -ldl.
#include <dlfcn.h> void *lib = dlopen("libm.so.6", RTLD_NOW); double (*cosine)(double) = (double (*)(double))dlsym(lib, "cos");
Example: calling a function from libm
Read-only. Loads the math library, looks up cos, calls it and closes the library.
#include <dlfcn.h> #include <stdio.h> int main(void) { void *lib = dlopen("libm.so.6", RTLD_NOW); if (lib == NULL) { fprintf(stderr, "dlopen failed: %s\n", dlerror()); return 1; } dlerror(); /* clear old error state */ double (*cosine)(double) = (double (*)(double))dlsym(lib, "cos"); const char *problem = dlerror(); if (problem != NULL) { fprintf(stderr, "dlsym failed: %s\n", problem); dlclose(lib); return 1; } printf("cos(0) = %.1f\n", cosine(0.0)); /* cos(0) = 1.0 */ dlclose(lib); return 0; }
Example: a tiny plugin
Read-only. Two files: the plugin, built as a shared library, and the host that loads it.
/* plugin.c build: gcc -shared -fPIC plugin.c -o libgreet.so */ #include <stdio.h> void greet(const char *name) { printf("Hello from the plugin, %s!\n", name); }
/* host.c build: gcc host.c -o host -ldl run: ./host */ #include <dlfcn.h> #include <stdio.h> int main(void) { void *lib = dlopen("./libgreet.so", RTLD_NOW); /* ./ = look in this folder */ if (!lib) { fprintf(stderr, "%s\n", dlerror()); return 1; } void (*greet)(const char *) = (void (*)(const char *))dlsym(lib, "greet"); if (greet) { greet("C"); /* prints: Hello from the plugin, C! */ } dlclose(lib); return 0; }
Syntax
void *dlopen(const char *filename, int flags); void *dlsym(void *restrict handle, const char *restrict symbol); int dlclose(void *handle); char *dlerror(void);
| Name | Description |
|---|---|
filename |
Path or library name. A name containing a slash is used as a path; otherwise the loader searches its standard directories (LD_LIBRARY_PATH, system paths). NULL returns a handle for the main program and its already loaded libraries. |
flags |
Exactly one of RTLD_LAZY (resolve functions on first call) or RTLD_NOW (resolve everything now), optionally with RTLD_GLOBAL (make symbols available to later libraries) or RTLD_LOCAL (the default). |
handle |
A value from dlopen, or the special RTLD_DEFAULT / RTLD_NEXT (GNU, also on BSD and macOS). |
symbol |
The name of the function or variable, as an unmangled string. |
Returns: dlopen returns a handle, or NULL on failure. dlsym returns the symbol's address, or NULL. dlclose returns 0 on success. dlerror returns a message about the most recent failure and clears it; it returns NULL if nothing went wrong since the last call.
Errors / undefined behavior: calling a function through a pointer of the wrong type is undefined behavior. A symbol whose value can legitimately be NULL needs the dlerror() check shown above. Using a handle or a symbol after dlclose is undefined behavior.
Usage notes
- Function pointer casts. ISO C does not allow converting
void *to a function pointer, but POSIX requiresdlsymto work this way. Cast to the exact function type and keep the cast in one place;-Wpedanticmay warn. - Check
dlerror().NULLfromdlsymcan mean "not found" or a symbol that really isNULL. Calldlerror()before, then again after, to tell them apart. RTLD_NOWfinds problems early. WithRTLD_LAZY, a missing function fails the first time the plugin calls it, possibly in the middle of work.- C++ names are mangled. Export plugin functions as
extern "C", ordlsymcannot find them by their source name. - Security. Loading a library runs its initializers with your privileges. Never
dlopena path an attacker can influence, and prefer absolute paths over searching. - Unloading is not always real. If other code still references the library, or it uses thread-local storage or
atexithandlers,dlclosemay leave it mapped. Plan to unload only simple plugins. - Thread safety.
dlopen,dlsymanddlcloseare thread-safe in glibc;dlerrorreturns thread-local messages. - Windows uses
LoadLibrary,GetProcAddressandFreeLibraryfor the same job.
Related
- mmap, which the loader uses to map the library
- Function pointers and Callbacks
- Compiling and linking and Compilers
- Tutorial: Function pointers and Build tools