Documenting C++ Code with Sphinx
Documenting is an important part of the code development process. In this post, documenting the C++ code with Sphinx is demonstrated.
Sphinx is a tool that makes it easy to create intelligent and beautiful documentation, written by Georg Brandl and licensed under the BSD license. It was originally created for the Python documentation. Sphinx can not extract the API documentation from C++ files and it requires an external tool for generating RST directives from them. Doxygen tool and Breathe plugin are utilized for that purpose.
Doxygen is a standard tool for generating documentation from annotated code. It is used to generate XML output that can then be parsed by the Breathe plugin, which provides the RST directives used to embed the code comments into the Sphinx documentation.
The steps required for creating the documentation:
- Create doxyfile for the project
- Update the Breathe config
- Create RST files with the API description using Breathe directives
- Generate the project documentation
Install Doxygen
In Ubuntu Doxygen can be installed with following command line:
apt-get install doxygen
Install Sphinx
Sphinx can be installed with pip:
pip3 install sphinx
Install Breathe
Breathe plugin can be installed with pip:
pip3 install breathe
Install Read Read the Docs Sphinx Theme
Read the Docs Theme can be installed with pip:
pip3 install sphinx-rtd-theme
Generate Doxyfile
A doxyfile is a Doxygen configuration file that provides all the necessary information about the documented project. It is used to generate Doxygen output in the chosen format.
Doxyfile can be generated with the following command:
doxygen -g Doxyfile.in
In the generated configuration file, input file locations and output folder should be given and the generating xml option should be enabled.
GENERATE_XML = YES
INPUT = ../include/my_project
OUTPUT_DIRECTORY = doc_out
Create Breathe Configuration
Create RST API Documentation
To generate the Sphinx API documentation, you should use the directives provided by the Breathe plugin. A complete list of Breathe directives can be found in the https://breathe.readthedocs.io/en/latest/directives.html
Generate the Documentation
First, doxygen tool is used to generate documentation with the given Doxyfile.in configuration file:
doxygen Doxyfile.in
Documentation is generated under the doc_out folder and documents can be accessed through the doc_out/html/index.html file. Doxygen document can be seen in the image below:
Then, sphinx documentation can be generated with the following command:
sphinx-build -b html -Dbreathe_projects.my_project=doc_out/xml . doc_out/sphinx/
Sphinx document is generated under the doc_out folder and document can be seen in the image below:
Document generating process can be automated in the building phase of the project by adding commands to the CMakeLists.txt file. For the complete example you can check the following repo:
References
https://www.sphinx-doc.org/en/master/