Skip to content

Instantly share code, notes, and snippets.

@kolodziej
Created November 21, 2014 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kolodziej/29feeeb0d1c535b03ed6 to your computer and use it in GitHub Desktop.
Save kolodziej/29feeeb0d1c535b03ed6 to your computer and use it in GitHub Desktop.
Tutorial 1 for C++ modular application
#include <dlfcn.h>
#include <iostream>
#include "ModuleBase.hpp"
int main(int argc, char ** argv)
{
if (argc == 1)
{
std::cerr << "Usage: " << argv[0] << " modules...\n";
return 1;
}
for (int i = 1; i < argc; ++i)
{
void* shared_library = dlopen(argv[i], RTLD_LAZY);
ModuleBase* (*loader)() = reinterpret_cast<ModuleBase* (*)()>(dlsym(shared_library, "loader"));
ModuleBase* module;
if (loader)
{
module = loader();
module->run();
} else
{
std::cerr << "Error while loading: " << argv[i] << "\n";
}
}
return 0;
}
#ifndef MODULE_BASE_HPP
#define MODULE_BASE_HPP
class ModuleBase
{
public:
virtual void run() = 0;
};
#endif
#include "ModuleBase.hpp"
#include <iostream>
class ModuleSoph :
public ModuleBase
{
public:
void run()
{
std::cout << "Sophisticated module is running!\n";
}
};
extern "C" ModuleBase* loader()
{
ModuleBase* m = new ModuleSoph;
return m;
}
#include "ModuleBase.hpp"
#include <iostream>
class ModuleStart :
public ModuleBase
{
public:
void run()
{
std::cout << "Start module is running!\n";
}
};
extern "C" ModuleBase* loader()
{
ModuleBase* m = new ModuleStart;
return m;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment