Skip to content
reroman edited this page Mar 10, 2017 · 2 revisions

CPP-PluginApp

Introduction

This program is an example of how to create an app with plugins in C++. The program is about to calculate the area and perimeter of some figures using plugins located in the 'plugins' folder.

To build the main program is necessary two classes:

  • plugin::Figure: It's an abstract class and every plugin must extends of it. Moreover, the plugins must override three methods:

    1. void setData();
    2. double area() const;
    3. double perimeter() const;
  • plugin::FigureLoader: It's a helper to load external libraries.

Compilation

Clone the repository

First of all it's necessary to clone the repository. So in your terminal:

$ git clone https://github.com/reroman/CPP-PluginApp.git
$ cd CPP-PluginApp

Compiling with cmake

It's a good idea build the project in a different folder, so let's create it and then execute cmake:

$ mkdir build
$ cd build
$ cmake ..

By default some plugins are built too, but if you don't want to, you can deactivate them setting up the BUILD_PLUGINS option to OFF:

$ cmake -DBUILD_PLUGINS=OFF ..

Compiling manually with GCC

On Unix-like:

$ g++ -std=c++11 main.cpp FigureLoader.cpp -o figures -ldl
$ cd plugins
$ g++ -std=c++11 -fPIC -shared -I.. square.cpp -o libsquare.so
$ g++ -std=c++11 -fPIC -shared -I.. equilateraltriangle.cpp -o libequilateraltriangle.so

On windows:

> g++ -std=c++11 -U__STRICT_ANSI__ main.cpp FigureLoader.cpp -o figures.exe
> cd plugins
> g++ -std=c++11 -shared -I.. square.cpp -o libsquare.dll
> g++ -std=c++11 -shared -I.. equilateraltriangle.cpp -o libequilateraltriangle.dll

Execution

Change to the directory where the executable is and then:

$ ./figures

On Windows you can also use double click.

Create a new plugin

As I say above, to create a new plugin for the app it's necessary to extend the Figure class and override its abstract methods. For example, to create a plugin with circle support, the new file (circle.cpp) could look like this:

#include "Figure.hpp"
#include <iostream>
using namespace std;
using namespace plugin;

#define PI 3.14159265358

class Circle: public Figure
{
  public:
    Circle() // To set the name of the figure
      : Figure( "Circle" ){}

    void setData() override // Ask data to the user
    {
      cout << "Give the radius: ";
      cin >> radius;
    }

    double area() const override // Calculates the area
    {
      return PI * radius * radius;
    }

    double perimeter() const override // Calculates the perimeter
    {
      return PI * 2.0 * radius;
    }

  private:
    double radius;
};

DEFAULT_REGISTER_FIGURE( Circle ); // Registers the new Figure

The manual compilation is the same like the other ones above. The new file (.dll or .so) only needs to be placed in the 'plugins' folder and restart the main program. The app will load the new feature automatically.

Author

Ricardo Román <reroman4@gmail.com>