Skip to content

Instantly share code, notes, and snippets.

@ascopes
Last active January 11, 2026 09:55
Show Gist options
  • Select an option

  • Save ascopes/6f1bf15bdab33758dcfb7e3746e2f90f to your computer and use it in GitHub Desktop.

Select an option

Save ascopes/6f1bf15bdab33758dcfb7e3746e2f90f to your computer and use it in GitHub Desktop.
Loads a shared object and executes code inside it
#include <assert.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
const char *const module = "./module.so";
typedef void (*run_func)(void);
int main(void) {
printf("Loading %s\n", module);
char *error;
void *handle = dlopen(module, RTLD_LOCAL | RTLD_NOW);
if ((error = dlerror()) != nullptr) {
perror(error);
return EXIT_FAILURE;
}
run_func run = dlsym(handle, "run");
if ((error = dlerror()) != nullptr) {
perror(error);
return EXIT_FAILURE;
}
run();
dlclose(handle);
}
CC := clang
CFLAGS := -Wall -Wextra -Werror -std=c23 -g
.PHONY: build clean
build: dynload.exe module.so
clean:
$(RM) *.o *.so *.exe
dynload.exe: dynload.o
$(CC) -o $@ $^ $(LDFLAGS)
module.so: module.o
$(CC) -shared -o $@ $^ $(LDFLAGS)
%.o: %.c
$(CC) $(CFLAGS) -o $@ -c $<
#include <stdio.h>
void run(void) {
printf("Hello, from inside module.so\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment