// plugin.h
#ifndef PLUGIN_H
#define PLUGIN_H
// Каждый плагин должен экспортировать:
// void info(void);
#endif
------------------
#include <stdio.h>
void info(void) {
printf("Плагин: Math Utilities\n");
printf("Версия: 1.0\n");
printf("Автор: Иванов И.И.\n");
printf("Описание: математические функции\n");
}
---------------------
#include <stdio.h>
void info(void) {
printf("Плагин: String Extensions\n");
printf("Версия: 2.1\n");
printf("Автор: Петров П.П.\n");
printf("Описание: работа со строками\n");
}
-----------------------
// Не содержит info() — только для теста
int dummy = 42;
-----------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h> // dlopen, dlsym, dlclose
#include <dirent.h> // opendir, readdir
// Проверяет, оканчивается ли файл на .so
int is_so_file(const char *filename) {
const char *dot = strrchr(filename, '.');
return (dot && strcmp(dot, ".so") == 0);
}
// Загружает один плагин и вызывает info()
void process_plugin(const char *path) {
void *handle;
void (*info_func)(void);
char *error;
printf("\n--- Плагин: %s ---\n", path);
handle = dlopen(path, RTLD_NOW);
if (!handle) {
printf("Ошибка загрузки: %s\n", dlerror());
return;
}
dlerror(); // очищаем предыдущую ошибку
info_func = (void (*)(void)) dlsym(handle, "info");
error = dlerror();
if (error) {
printf("Функция info не найдена: %s\n", error);
} else {
info_func(); // вызываем!
}
dlclose(handle); // выгружаем библиотеку
}
int main(int argc, char *argv[]) {
const char *dir = ".";
if (argc > 1) dir = argv[1];
DIR *d = opendir(dir);
if (!d) { perror("opendir"); exit(EXIT_FAILURE); }
struct dirent *entry;
while ((entry = readdir(d)) != NULL) {
if (entry->d_type == DT_REG && is_so_file(entry->d_name)) {
char fullpath[1024];
snprintf(fullpath, sizeof(fullpath),
"%s/%s", dir, entry->d_name);
process_plugin(fullpath);
}
}
closedir(d);
return 0;
}
----------------------------
# Компилируем каждый плагин в .so
gcc -c -fPIC plugin_math.c -o plugin_math.o
gcc -shared -o plugin_math.so plugin_math.o
gcc -c -fPIC plugin_string.c -o plugin_string.o
gcc -shared -o plugin_string.so plugin_string.o
gcc -c -fPIC plugin_broken.c -o plugin_broken.o
gcc -shared -o plugin_broken.so plugin_broken.o
--------------------------
gcc plugin_loader.c -ldl -o plugin_loader
./plugin_loader
---------------------
./plugin_loader /path/to/plugins