CodeBlanks Logo Icon CodeBlanks

dlsym

Learn to resolve symbols with dlsym.

What is dlsym?

dlsym retrieves the address of a symbol (function or variable) from a loaded library. You get the address of printf with void *sym = dlsym(h, "printf"). The return is void *; you cast it to the type you want.

On failure it returns NULL; but the real check is done with dlerror (next lesson). You can cast the address obtained via dlsym to a function pointer and call it: typedef void (*Fn)(void); Fn f = (Fn)dlsym(h, "foo"); f();. For testing, dlsym(h, "printf") usually succeeds from the main program.

The symbol resolution pattern

The typical flow: void *h = dlopen(NULL, RTLD_LAZY);, void *sym = dlsym(h, "printf");, printf("symbol found\n");, if (h) dlclose(h);. This prints that the symbol was resolved.

Actually calling the symbol comes in the next lesson; here we just show the address being fetched. The output is deterministic: printf is always found in the main program. If you look for a different symbol and it is not found, sym becomes NULL; then dlerror gives the error message.

Practice Resolve a symbol

Get a handle with void *h = dlopen(NULL, RTLD_LAZY);. Resolve the printf symbol with void *sym = dlsym(h, "printf");. Print with printf("symbol found\n");. Close with if (h) dlclose(h);.

Starter code

main.c
#include <stdio.h>
#include <dlfcn.h>

// Load library
// Resolve symbol
// Print and close

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <dlfcn.h>

int main(void) {
    void *h = dlopen(NULL, RTLD_LAZY);
    void *sym = dlsym(h, "printf");
    printf("symbol found\n");
    if (h) dlclose(h);
    return 0;
}

Expected output

symbol found

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match dlsym parts

Term Meaning
dlsym Symbol address
void * Return type
cast Type conversion
NULL Error

2 What type does dlsym return?

  • int
  • void * Correct answer
  • char *
  • long

Explanation: dlsym returns void *; you cast to use it.

3 dlsym call

Question
void *sym = ____(h, "printf");
Answer
void *sym = dlsym(h, "printf");

Explanation: dlsym gets the symbol address from the h handle.

All lessons in Advanced