How to generate plantuml class diagrams from c++ code using hpp2plantuml
Introduction
Accurate documentation is vital to any software project. However, this process can be time consuming and is often overlooked specially in projects with a tight schedule and budget. Generating documentation like UML diagrams from source code can definitely save a lot of time.
We would like to show you a way to do this for C++ projects by using hpp2plantuml https://hpp2plantuml.readthedocs.io/en/latest/index.html
Installation
sudo apt install plantuml pip3 install hpp2plantuml
Structure
Consider the following files
IAnimal.hpp
#ifndef IANIMAL_HPP #define IANIMAL_HPP class IAnimal { public: virtual ~IAnimal() {} virtual void makeSound() = 0; }; #endif
Cat.hpp
#ifndef CAT_HPP #define CAT_HPP #include "IAnimal.hpp" #include <iostream> class Cat : public IAnimal { public: void makeSound() override { std::cout << "Meow!" << std::endl; } }; #endif
Dog.hpp
#ifndef DOG_HPP #define DOG_HPP #include "IAnimal.hpp" #include <iostream> class Dog : public IAnimal { public: void makeSound() override { std::cout << "Woof!" << std::endl; } }; #endif
AnimalShelter.hpp
#ifndef ANIMAL_SHELTER_HPP #define ANIMAL_SHELTER_HPP #include "IAnimal.hpp" #include <vector> #include <memory> class AnimalShelter { private: std::vector<std::shared_ptr<IAnimal>> animals; public: void addAnimal(std::shared_ptr<IAnimal> animal) { animals.push_back(animal); } void makeAllSounds() { for (const auto& animal : animals) { animal->makeSound(); } } }; #endif
Generate diagram
Using the following command you can generate the UML class diagram
hpp2plantuml -i "*.hpp" -o out.puml
To create an svg image do
plantuml -tpng out.puml
This will produce the diagram like the following
If you want to produce an svg pass the -tsvg flag to the plantuml binary
The program is also able to identify namespaces and render them as modules for example: