CodeBlanks Logo Icon CodeBlanks

Plugin system

Learn to build a plugin system with dlopen.

Plugin system

A plugin system is an architecture that allows adding features without recompiling the main program. You load the plugin file with dlopen, get its entry function with dlsym, and call it via a function pointer. When done, close with dlclose.

The plugin author exports a function with a known name in the plugin file, e.g. void plugin_init(void). The main program looks up this name with dlsym. The pointer type is defined with typedef void (*PluginFn)(void);. For testing, you can use the main program's symbols instead of a real plugin; the output is deterministic.

The plugin invocation pattern

The typical flow: define the type with typedef void (*PluginFn)(void);. Load with void *h = dlopen(NULL, RTLD_LAZY);. Get the symbol with PluginFn fn = (PluginFn)dlsym(h, "printf"); and cast. Show usage with (void)fn;. Print with printf("plugin loaded\n");. Close with if (h) dlclose(h);.

In real apps, you call fn() to invoke the plugin function; but for testing, just showing the load is enough. The output is deterministic. If the plugin file is missing, you can catch the error with dlerror and switch to an alternate path.

Practice Load a plugin

Define the type with typedef void (*PluginFn)(void);. Load with void *h = dlopen(NULL, RTLD_LAZY);. Get the symbol with PluginFn fn = (PluginFn)dlsym(h, "printf");. Show usage with (void)fn;. Print with printf("plugin loaded\n");. Close with if (h) dlclose(h);.

Starter code

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

// Define plugin type
// Load library and get symbol
// Print and close

int main(void) {
    return 0;
}

Sample solution

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

typedef void (*PluginFn)(void);

int main(void) {
    void *h = dlopen(NULL, RTLD_LAZY);
    PluginFn fn = (PluginFn)dlsym(h, "printf");
    (void)fn;
    printf("plugin loaded\n");
    if (h) dlclose(h);
    return 0;
}

Expected output

plugin loaded

Questions and answers

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

1 Match plugin parts

Term Meaning
dlopen Loads plugin
dlsym Gets entry
PluginFn Pointer type
dlclose Closes

2 Which type is the plugin entry function defined with?

  • PluginFn Correct answer
  • int
  • char
  • void

Explanation: PluginFn is the function pointer type for the plugin entry.

3 Plugin type

Question
typedef void (*____)(void);
Answer
typedef void (*PluginFn)(void);

Explanation: PluginFn is the plugin function pointer type.

All lessons in Advanced