Skip to content

Instantly share code, notes, and snippets.

@yvbbrjdr
Last active October 15, 2019 23:40
Show Gist options
  • Save yvbbrjdr/fdc59125c39bf32962a684ae96846a2f to your computer and use it in GitHub Desktop.
Save yvbbrjdr/fdc59125c39bf32962a684ae96846a2f to your computer and use it in GitHub Desktop.
A simple hello world program in Linux C++.
#include "plugininterface.h"
#include <iostream>
using namespace std;
class HelloPlugin : public PluginInterface {
public:
virtual void f()
{
cout << "hello, world" << endl;
}
};
extern "C" {
PluginInterface *plugin_create()
{
return new HelloPlugin();
}
void plugin_destroy(PluginInterface *plugin)
{
delete plugin;
}
}
#include <cstdio>
#include <cstdlib>
#include <dlfcn.h>
#include "plugininterface.h"
typedef PluginInterface *(*PluginCreate)();
typedef void (*PluginDestroy)(PluginInterface *);
int main()
{
void *handle = dlopen("./helloplugin.so", RTLD_LAZY);
if (handle == nullptr) {
fprintf(stderr, "dlopen: %s\n", dlerror());
exit(EXIT_FAILURE);
}
PluginCreate plugin_create = reinterpret_cast<PluginCreate>(dlsym(handle, "plugin_create"));
if (plugin_create == nullptr) {
fprintf(stderr, "dlsym: %s\n", dlerror());
exit(EXIT_FAILURE);
}
PluginDestroy plugin_destroy = reinterpret_cast<PluginDestroy>(dlsym(handle, "plugin_destroy"));
if (plugin_destroy == nullptr) {
fprintf(stderr, "dlsym: %s\n", dlerror());
exit(EXIT_FAILURE);
}
PluginInterface *plugin = plugin_create();
plugin->f();
plugin_destroy(plugin);
dlclose(handle);
exit(EXIT_SUCCESS);
}
CXX=g++
CFLAGS=-Wall -Wextra -O3
all: hello helloplugin.so
hello: main.cpp plugininterface.h
$(CXX) $(CFLAGS) -ldl $< -o $@
helloplugin.so: helloplugin.cpp plugininterface.h
$(CXX) $(CFLAGS) -shared -fPIC $< -o $@
clean:
rm -f hello helloplugin.so
#ifndef PLUGININTERFACE_H
#define PLUGININTERFACE_H
class PluginInterface {
public:
virtual void f() = 0;
virtual ~PluginInterface() {}
};
#endif // PLUGININTERFACE_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment