Doxygen tool for create documentation - GitMasterNikanjam/C_WiKi GitHub Wiki
Doxygen is a popular documentation generation tool, primarily used for writing software documentation directly from the source code. It supports a wide range of programming languages such as C, C++, Java, Python, Fortran, and more. Here's an overview of the tool:
-
Automatic Documentation Generation: Doxygen can automatically extract comments and code structure from the source files to generate documentation in various formats like HTML, LaTeX, PDF, and more.
-
Supports Multiple Languages: While Doxygen is most commonly used for C, C++, and Java, it supports a variety of programming languages such as Python, IDL, VHDL, and more.
-
Cross-Referencing: Doxygen allows you to create hyperlinks between documented code elements, making it easier to navigate the documentation. It can cross-reference classes, files, namespaces, and functions.
-
Graphical Class Hierarchy: Doxygen can generate class diagrams and include them in the documentation, providing a visual representation of the class structure and inheritance.
-
Configurable Output Formats:
- HTML: Ideal for web-based documentation.
- LaTeX: Can be converted to PDF.
- RTF/Word: Can be exported to Microsoft Word.
- Man pages: For Unix-based man pages.
-
Customizable Documentation Style: Doxygen allows you to customize the way the documentation is presented by using configuration files. It also supports markup commands that allow additional formatting like bold, italic, code blocks, and even math formulas (via LaTeX).
-
Integration with Version Control: Doxygen can be integrated with version control systems, helping in tracking documentation changes along with code evolution.
-
Source Code Parsing: Doxygen parses source code to extract the structure (like classes, functions, and variables) and documentation comments.
-
Documentation Tags: Developers use specific tags (like
@param
,@return
,@brief
, etc.) to describe different elements of the code. These tags allow Doxygen to generate detailed documentation about function parameters, return values, and descriptions. -
Configuration File (
Doxyfile
): TheDoxyfile
is a configuration file that controls how Doxygen behaves. It includes settings for which files to process, what format to output, and options for diagrams or cross-references. -
Generating Documentation: Once set up, running Doxygen generates the desired documentation format. For HTML, a set of web pages is created, while for LaTeX, a PDF can be created via the LaTeX toolchain.
- API Documentation: Many open-source projects use Doxygen to document their APIs.
- Internal Documentation: Companies use Doxygen for documenting internal libraries, making it easier for teams to understand and work with large codebases.
- Research and Academic Projects: Doxygen is often used in academia for documenting research code, particularly in fields like simulations and numerical analysis.
It is particularly useful for projects where maintaining consistent, up-to-date documentation alongside the code is critical.
To compile the LaTeX output from Doxygen into a PDF on Windows, you'll need to install a LaTeX distribution. Here's how to do it:
-
MiKTeX is a popular LaTeX distribution for Windows:
- Download and install MiKTeX from miktex.org.
- During installation, select the option to install missing packages on the fly, so any required LaTeX packages are downloaded automatically.
- While MiKTeX provides the command-line tools to compile LaTeX documents, you might want a GUI editor. TeXworks is bundled with MiKTeX, or you can use TeXstudio:
- Download TeXstudio from texstudio.org.
- Run Doxygen to generate the LaTeX output as explained earlier. It will create a
latex
folder containing the.tex
files (includingrefman.tex
).
- Open a command prompt and navigate to the
latex
directory:cd path\to\your\latex\folder
- Use
pdflatex
(included with MiKTeX) to compile the LaTeX file:(Running it multiple times helps resolve cross-references.)pdflatex refman.tex pdflatex refman.tex pdflatex refman.tex
- After compiling, the
refman.pdf
file will be created in the samelatex
folder. - You can open it with any PDF reader.
Annotating your C++ code for Doxygen involves adding special comment blocks and tags to describe the various elements of your code, such as functions, classes, and variables. These annotations guide Doxygen in generating meaningful and organized documentation. Here's a guide on how to properly annotate a C++ program for Doxygen:
Doxygen recognizes specific types of comment blocks. There are two main styles of comments:
-
C-style comments:
/** ... */
-
C++-style comments:
///
Both styles are used to provide inline documentation. Here’s how you use them:
/**
* This is a Doxygen-style comment block for a class or function.
* It starts with a double asterisk and can span multiple lines.
*/
or:
/// This is a single-line Doxygen comment for a function or variable.
Doxygen uses various tags to annotate and describe your code. Below are common tags for different code elements:
At the beginning of your file, you can document the purpose of the file with @file
:
/**
* @file my_program.cpp
* @brief This file contains the main logic for the program.
*/
You can document a class and its members like this:
/**
* @class MyClass
* @brief This class performs operations on data.
*/
class MyClass {
public:
/**
* @brief Constructor for MyClass.
*/
MyClass();
/**
* @brief Sets the value of the internal data member.
*
* @param value The new value to be set.
*/
void setValue(int value);
/**
* @brief Gets the value of the internal data member.
*
* @return The value of the internal data member.
*/
int getValue() const;
private:
int data; ///< Internal data member of the class.
};
Functions are documented by specifying the parameters and return types:
/**
* @brief Adds two numbers and returns the sum.
*
* @param a The first number.
* @param b The second number.
* @return The sum of a and b.
*/
int add(int a, int b) {
return a + b;
}
Here’s a list of commonly used Doxygen tags:
-
@brief
: A short description of the entity (function, class, variable). -
@param [name]
: Describes the function parameter. -
@return
: Describes the return value of a function. -
@file
: Describes the file itself (useful at the top of a file). -
@class
: Used to document a class. -
@warning
: Generates a warning in the documentation. -
@todo
: Marks parts of the code that need further work.
/**
* @brief Subtracts the second number from the first.
*
* This function subtracts two integers and returns the result.
* It throws an exception if overflow occurs.
*
* @param a The minuend.
* @param b The subtrahend.
* @return The result of a - b.
* @throws std::overflow_error If the result overflows.
*/
int subtract(int a, int b) {
if (b > a) {
throw std::overflow_error("Subtraction overflow!");
}
return a - b;
}
You can document member variables or constants as well:
/**
* @brief The maximum allowed value.
*/
const int MAX_VALUE = 100;
/**
* @brief The current state of the system.
*/
bool system_state;
You can add more detailed descriptions of classes or functions using the @details
tag:
/**
* @class Circle
* @brief A class to represent a circle.
*
* @details This class provides methods to compute the area and circumference
* of a circle. It also supports scaling and comparisons between circles.
*/
class Circle {
// ...
};
You can group code into logical modules with @defgroup
and @ingroup
.
/**
* @defgroup MathFunctions Mathematical Functions
* @{
*/
/**
* @brief Multiplies two numbers.
* @param a The first number.
* @param b The second number.
* @return The product of a and b.
*/
int multiply(int a, int b) {
return a * b;
}
/** @} */ // end of MathFunctions
If there’s functionality you intend to add in the future, you can use @todo
to document it:
/**
* @brief Finds the maximum of two numbers.
*
* @todo Optimize the function for performance.
*/
int max(int a, int b) {
return (a > b) ? a : b;
}
Doxygen can automatically generate class inheritance and collaboration diagrams if graphing tools like Graphviz are enabled.
/**
* @class Derived
* @brief A derived class that inherits from Base.
*
* @dotfile inheritance.dot
*/
class Derived : public Base {
// ...
};
You can write LaTeX-style mathematical formulas using @f$
and @f[ ... @f]
for inline and block formulas, respectively:
/**
* @brief Calculates the square of a number.
*
* The square of a number is given by @f$ x^2 @f$.
*
* @param x The number to be squared.
* @return The square of x.
*/
int square(int x) {
return x * x;
}
After adding these annotations, run Doxygen with a configuration file (Doxyfile
) that defines how it should parse the code and generate output. To generate a PDF from LaTeX output:
- Ensure you have the
GENERATE_LATEX
flag set toYES
in theDoxyfile
. - After running Doxygen, compile the LaTeX files into a PDF using a tool like
pdflatex
.
By properly annotating your code with Doxygen comments, you create self-maintaining documentation that grows as your project evolves, making it easier for others (and yourself) to understand the code structure and purpose.
For advanced documentation in C and C++ programs using Doxygen, you can leverage additional features and techniques to enhance the clarity and usability of your generated documentation. Here’s an overview of more advanced annotation techniques:
Using namespaces can help organize code logically. Documenting them is crucial, especially in large projects.
/**
* @namespace MyNamespace
* @brief This namespace contains functions and classes related to mathematics.
*/
namespace MyNamespace {
/**
* @brief Computes the factorial of a number.
* @param n The number to compute the factorial for.
* @return The factorial of n.
*/
int factorial(int n);
}
You can create logical groups of related functions, classes, or files, allowing for better organization in the generated documentation. Use @defgroup
and @ingroup
.
/**
* @defgroup Geometry Geometry Functions
* @{
*/
/**
* @brief Calculates the area of a rectangle.
* @param width Width of the rectangle.
* @param height Height of the rectangle.
* @return Area of the rectangle.
*/
double rectangleArea(double width, double height);
/**
* @brief Calculates the area of a circle.
* @param radius Radius of the circle.
* @return Area of the circle.
*/
double circleArea(double radius);
/** @} */ // end of Geometry
You can use the @see
tag to provide references to related classes, functions, or documentation entries. This improves navigability in the documentation.
/**
* @brief Computes the square root of a number.
* @param x The number for which to compute the square root.
* @return The square root of x.
* @see pow() for power calculations.
*/
double squareRoot(double x);
Doxygen supports documenting overloaded functions and templates well.
/**
* @brief Computes the maximum of two values.
*
* This function is overloaded to handle both integers and doubles.
*
* @param a First value.
* @param b Second value.
* @return The maximum of a and b.
*/
int max(int a, int b);
/**
* @brief Computes the maximum of two values.
*
* @param a First value.
* @param b Second value.
* @return The maximum of a and b.
*/
double max(double a, double b);
/**
* @brief A generic max function for templates.
*
* @tparam T Type of the values.
* @param a First value.
* @param b Second value.
* @return The maximum of a and b.
*/
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
You can provide important notes and warnings in your documentation.
/**
* @brief Divides two numbers.
*
* @note Ensure the denominator is not zero to avoid division by zero.
* @warning This function does not handle complex numbers.
* @param numerator The number to be divided.
* @param denominator The number to divide by.
* @return The result of the division.
*/
double divide(double numerator, double denominator);
You can use LaTeX within Doxygen comments for more complex formatting, such as equations, matrices, or custom symbols.
/**
* @brief Calculates the distance between two points.
*
* The distance \( d \) between two points \( (x_1, y_1) \) and \( (x_2, y_2) \) is given by:
* \[
* d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}
* \]
* @param x1 The x-coordinate of the first point.
* @param y1 The y-coordinate of the first point.
* @param x2 The x-coordinate of the second point.
* @param y2 The y-coordinate of the second point.
* @return The distance between the two points.
*/
double distance(double x1, double y1, double x2, double y2);
You can document different sections of code conditionally using preprocessor directives. This can be useful for cross-platform code.
#ifdef USE_FEATURE_X
/**
* @brief Performs operation X.
* @details This function is only available when USE_FEATURE_X is defined.
*/
void operationX();
#endif
For documenting complex class hierarchies, you can use Doxygen to generate inheritance and collaboration diagrams, provided Graphviz is installed.
/**
* @class Base
* @brief Base class for all shapes.
*/
class Base {
public:
virtual double area() const = 0; ///< Pure virtual function.
};
/**
* @class Circle
* @brief Represents a circle, derived from Base.
*/
class Circle : public Base {
public:
double area() const override; ///< Calculates area of the circle.
};
You can document enums and structs similarly to classes.
/**
* @enum Color
* @brief Represents different colors.
*/
enum Color {
RED, ///< Red color
GREEN, ///< Green color
BLUE ///< Blue color
};
/**
* @struct Point
* @brief Represents a point in 2D space.
*/
struct Point {
double x; ///< X coordinate
double y; ///< Y coordinate
};
If your functions throw exceptions, document them clearly to inform users of potential issues.
/**
* @brief Parses an integer from a string.
*
* @param str The string to parse.
* @return The parsed integer.
* @throws std::invalid_argument If the string cannot be converted to an integer.
* @throws std::out_of_range If the integer is out of range.
*/
int parseInt(const std::string& str);
You can include version control information within your documentation.
/**
* @file my_program.cpp
* @brief Main program file.
*
* @version 1.0
* @date 2024-09-26
* @author Your Name
*/
Doxygen can generate indexes and user manuals, which you can enhance using @index
and @manual
.
/**
* @manual MyProgram User Manual
* @brief User manual for MyProgram.
*
* This manual provides information on how to use MyProgram, including installation and usage instructions.
*/
If using Markdown is preferable, you can mix Markdown syntax in your comments. Doxygen supports various Markdown features, including lists, tables, and code blocks.
/**
* @brief Summary of a feature.
*
* ## Features
* - Feature 1
* - Feature 2
* - Feature 3
*
* ### Example Usage
* ```cpp
* featureFunction();
* ```
*/
To enable and control the behavior of Doxygen, you may want to modify the Doxyfile
settings, such as:
-
EXTRACT_ALL
: To include all entities in the documentation. -
GENERATE_HTML
: To enable HTML output. -
GENERATE_LATEX
: To generate LaTeX output for PDF.
By using these advanced techniques for annotating your C and C++ programs, you can create comprehensive, well-organized, and user-friendly documentation that is invaluable for both current and future developers working with your code. Doxygen's extensive features can greatly improve code maintainability and ease of use, making it an essential tool for any serious development project. If you have specific examples or scenarios in mind, feel free to ask!
Managing files and creating a structured documentation system with Doxygen involves organizing your codebase effectively and configuring Doxygen to generate comprehensive and user-friendly documentation. Here’s a step-by-step guide on how to manage files and set up the main file for documentation using Doxygen:
Organize your project files into directories based on functionality, modules, or components. A common structure might look like this:
/MyProject
|-- /src
| |-- main.cpp
| |-- moduleA.cpp
| |-- moduleB.cpp
| `-- ...
|-- /include
| |-- moduleA.h
| |-- moduleB.h
| `-- ...
|-- /doc
| |-- Doxyfile
| `-- ...
`-- README.md
-
src/: Contains implementation files (
.cpp
). -
include/: Contains header files (
.h
). -
doc/: Contains the Doxygen configuration file (
Doxyfile
) and other documentation-related files.
Each module should have a corresponding header file that contains declarations for classes and functions. This allows Doxygen to easily associate documentation with the correct source files.
To create a Doxygen configuration file (Doxyfile
), run the following command in your project directory:
doxygen -g doc/Doxyfile
This generates a default Doxyfile
that you can customize.
Edit the Doxyfile
to configure Doxygen settings:
-
Project Information:
PROJECT_NAME = "My Project" PROJECT_BRIEF = "Brief description of my project." PROJECT_LOGO = "doc/logo.png" # Optional logo file
-
Input and Output Directories:
INPUT = src include # Source code directories OUTPUT_DIRECTORY = doc/html # Output directory for HTML documentation GENERATE_HTML = YES # Enable HTML output GENERATE_LATEX = YES # Enable LaTeX output for PDF
-
Recurse Subdirectories:
RECURSIVE = YES # Search subdirectories for source files
-
File Extensions:
EXTENSIONS = .cpp .h # Specify file extensions to document
-
EXTRACT_ALL:
EXTRACT_ALL = YES # Extract documentation for all entities
The main.cpp
file should contain the entry point of your program and can also serve as a central place to document the overall purpose of your application.
/**
* @file main.cpp
* @brief Main entry point of My Project.
*
* This file contains the main function that initializes the application
* and handles the overall flow of the program.
*
* @details This application does X, Y, and Z.
*
* @note This project is a work in progress.
*
* @warning Ensure to configure settings before running.
*/
#include "moduleA.h"
#include "moduleB.h"
int main() {
// Initialize application
return 0;
}
Each module (header file) should document its classes and functions. For example, in moduleA.h
:
/**
* @file moduleA.h
* @brief Module A provides functionality for X.
*
* Detailed description of module A.
*/
#ifndef MODULE_A_H
#define MODULE_A_H
/**
* @class ModuleA
* @brief Class to perform operation X.
*/
class ModuleA {
public:
/**
* @brief Executes operation X.
* @param param Description of the parameter.
*/
void execute(int param);
};
#endif // MODULE_A_H
After you have annotated your code and configured the Doxyfile
, run Doxygen to generate the documentation:
doxygen doc/Doxyfile
Once Doxygen finishes running, navigate to the output directory specified in the Doxyfile
(e.g., doc/html
) and open the index.html
file in a web browser to view the generated documentation.
Ensure that you regularly update the documentation as you modify the code. This includes adding new functions, modifying existing ones, or changing the overall structure of your project.
Consider automating the Doxygen documentation generation as part of your build process or CI/CD pipeline. This ensures that the documentation is always up to date.
Make use of advanced Doxygen tags to enhance your documentation further:
- @deprecated: Mark functions or classes that are deprecated.
- @internal: Document internal functions that should not be part of the public API.
- @example: Provide examples of how to use functions or classes.
- @include: Include documentation from other files or sections.
Here’s a simplified example of a Doxyfile
with comments explaining each option:
# Doxyfile for My Project
# Project Name
PROJECT_NAME = "My Project"
PROJECT_BRIEF = "Brief description of my project."
# Input Files
INPUT = src include
# Output Options
OUTPUT_DIRECTORY = doc/html
GENERATE_HTML = YES
GENERATE_LATEX = YES
# Recursion and File Types
RECURSIVE = YES
EXTENSIONS = .cpp .h
# Extract All Entities
EXTRACT_ALL = YES
# Diagrams and Graphs
HAVE_DOT = YES # Enable Graphviz support
GENERATE_TREEVIEW = YES # Generate tree view in documentation
By managing your files effectively and utilizing Doxygen’s capabilities, you can create clear, structured documentation for your C and C++ projects. This documentation will not only aid current developers in understanding the code but will also serve as a valuable resource for future maintainers. If you have specific scenarios or questions regarding file management or Doxygen configuration, feel free to ask!
Adding an "Example" tab in your Doxygen documentation involves creating a structured way to present code examples or usage instructions. This typically includes customizing the Doxygen configuration, writing example code, and creating links in your main documentation to point to these examples. Here’s how you can do it step-by-step:
First, ensure your Doxygen configuration file (Doxyfile
) is set up to include examples.
Make sure your Doxyfile
has HTML output enabled:
GENERATE_HTML = YES
You can specify a directory for your example files:
EXAMPLES = examples # Directory containing your example files
Create a directory called examples
in your project root. Inside this directory, you can add various example files (e.g., example1.cpp
, example2.cpp
, etc.).
Create example files in the examples
directory that demonstrate how to use your functions, classes, or modules.
/**
* @file example1.cpp
* @brief Example of using the ModuleA class.
*
* This example shows how to create an instance of ModuleA and use its methods.
*/
#include "moduleA.h"
#include <iostream>
int main() {
ModuleA obj;
obj.execute(5);
std::cout << "Example executed successfully!" << std::endl;
return 0;
}
You can create a section in your documentation that links to these example files. You can do this in the main file or wherever you want to reference the examples.
/**
* @file main.cpp
* @brief Main entry point of My Project.
*
* This file contains the main function that initializes the application
* and handles the overall flow of the program.
*
* @section examples Examples
*
* For example usage, see:
* - @ref example1 "Example 1: Using ModuleA"
*
* @note Make sure to check the examples directory for more sample code.
*/
#include "moduleA.h"
#include "moduleB.h"
int main() {
// Initialize application
return 0;
}
If you want to create a dedicated page for examples, you can do so by creating an HTML file and linking it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Examples - My Project</title>
</head>
<body>
<h1>Examples</h1>
<p>This page contains examples of how to use the various modules.</p>
<ul>
<li><a href="examples/example1.html">Example 1: Using ModuleA</a></li>
<li><a href="examples/example2.html">Example 2: Using ModuleB</a></li>
<!-- Add more examples as needed -->
</ul>
</body>
</html>
You can modify your custom_header.html
file to add a new tab for the examples section.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Project Documentation</title>
<link rel="stylesheet" href="style.css"> <!-- Link to any custom styles -->
</head>
<body>
<div id="custom-tab">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="custom_tab.html">Custom Tab</a></li>
<li><a href="example_page.html">Examples</a></li> <!-- Link to the Examples tab -->
</ul>
</div>
</body>
</html>
After setting everything up, run Doxygen to generate the documentation:
doxygen doc/Doxyfile
Navigate to the generated HTML output (typically in doc/html
), and open index.html
in a web browser. You should see your new "Examples" tab linked in the header, and clicking it should take you to your examples page or display the example files.
By following these steps, you can create an "Example" tab in your Doxygen-generated HTML documentation that provides users with practical code examples to reference. This improves the usability and clarity of your documentation, making it easier for users to understand how to implement your code. If you have further questions or specific needs, feel free to ask!
To set the main page of your C++ project for Doxygen documentation, you can create a dedicated page in your documentation that will serve as the main entry point. This can be done using a special Doxygen tag in a comment block or in a markdown file.
Here’s how you can do it:
You can define the main page by adding a \mainpage
command in a comment block in one of your source files or in a separate file (e.g., mainpage.dox
or README.md
).
/**
* \mainpage
* # My Project
*
* ## Overview
* Welcome to the documentation for the **My Project**. This project is a C++ program that does XYZ.
*
* ## Features
* - Feature 1
* - Feature 2
* - Feature 3
*
* ## Getting Started
* Here are some instructions to get you started with the project.
*
* ## Installation
* Describe the installation process here.
*
* ## Usage
* Example usage:
* ```bash
* ./my_program
* ```
*/
You can place this in a dedicated file like mainpage.dox
or README.md
:
/*! \mainpage My Project
# Welcome to My Project
This project is designed to ...
## Features:
- Feature 1
- Feature 2
## Installation:
Instructions to install this project...
*/
Ensure the file that contains the \mainpage
is included in your Doxygen configuration file (Doxyfile
).
- If you are using a markdown file (e.g.,
README.md
), make sure thatREADME.md
is listed in theINPUT
section of yourDoxyfile
. - If you’re using a
.dox
file, ensure that it’s included inINPUT
.
In the Doxyfile
, check the INPUT
field:
INPUT = path/to/mainpage.dox
If using a markdown file like README.md
, enable support for markdown:
USE_MDFILE_AS_MAINPAGE = README.md
After setting the main page, run Doxygen again to regenerate the documentation:
doxygen Doxyfile
This will set the page you defined as the main landing page when someone accesses the generated documentation.
To define a new page in Doxygen, you use the \page
command. This allows you to create custom documentation pages that are separate from your code comments and can contain detailed explanations, tutorials, or additional information about your project.
You can define a new page either within a code file, a .dox
file, or a markdown file.
/**
* \page MyPage My Custom Page
*
* # Welcome to My Custom Page
*
* This page explains details about a specific part of the project.
* You can add any kind of detailed documentation, images, or code examples here.
*
* ## Section 1
* Details about the first section of this page.
*
* ## Section 2
* More information about the second section.
*
* ### Code Example:
* ```cpp
* int example() {
* return 0;
* }
* ```
*/
If you prefer markdown syntax, you can create a new page with markdown files.
In a .md
file (e.g., MyPage.md
):
/*! \page MyPage My Custom Page
# My Custom Page
This is a new page in the Doxygen documentation. You can write text, include code snippets, and more.
```cpp
int foo() {
return 42;
}
*/
### 2. **Add the Page to the `Doxyfile`**
Ensure the file where you define the new page is included in the Doxygen configuration file (`Doxyfile`). Update the `INPUT` field to include the new file (if necessary):
```bash
INPUT = path/to/source/file.cpp path/to/MyPage.dox
You can refer to this page from other parts of the documentation using the \ref
command, like this:
/**
* You can find more details on \ref MyPage "this page".
*/
This links to the new page you created.
Finally, run Doxygen to regenerate the documentation:
doxygen Doxyfile
You can create multiple pages using \page
like this:
/**
* \page Introduction Introduction to the Project
*
* # Project Introduction
* This is an overview of the project.
*/
/**
* \page Installation Installation Guide
*
* # Installation Instructions
* Step-by-step guide on how to install the project.
*/
/**
* \page Usage Usage Guide
*
* # How to Use the Project
* Explanation on how to use the project.
*/
Each of these pages will appear separately in the generated Doxygen documentation, and you can link between them using \ref
.
To add pages in new tabs in Doxygen-generated documentation, you can leverage Doxygen's support for custom groups and navigation elements. Here's how you can organize your custom pages into tabs (which are essentially sections in the navigation sidebar) using Doxygen’s \defgroup
and \ingroup
commands.
You can group pages under a specific tab using \defgroup
. Each \defgroup
creates a new section in the navigation menu, which appears like a tab when the generated documentation is viewed.
/**
* \defgroup MyTab My Custom Tab
* This group will appear as a new tab in the documentation.
*/
Next, define the custom page and assign it to the group you just created using \ingroup
.
/**
* \page MyPage1 My First Custom Page
* \ingroup MyTab
*
* # My First Custom Page
* This page is assigned to "My Custom Tab".
*
* ## Content
* Detailed information about this page.
*/
/**
* \page MyPage2 My Second Custom Page
* \ingroup MyTab
*
* # My Second Custom Page
* This page is also assigned to "My Custom Tab".
*/
Make sure the files where you define your group and pages are included in the INPUT
section of your Doxyfile
.
For example:
INPUT = path/to/source_file.cpp path/to/custom_pages.dox
Run Doxygen to regenerate the documentation with the new structure:
doxygen Doxyfile
- A new tab labeled My Custom Tab will appear in the navigation sidebar.
- Under this tab, you’ll see My First Custom Page and My Second Custom Page listed.
/**
* \defgroup Guides User Guides
* This group contains various user guides and tutorials.
*/
/**
* \page InstallGuide Installation Guide
* \ingroup Guides
*
* # Installation Guide
* Steps on how to install the project.
*/
/**
* \page UsageGuide Usage Guide
* \ingroup Guides
*
* # Usage Guide
* Instructions on how to use the project.
*/
You can also create sub-tabs by defining groups within groups:
/**
* \defgroup AdvancedTopics Advanced Topics
* This is a parent tab.
*/
/**
* \defgroup NetworkTopics Networking Topics
* \ingroup AdvancedTopics
* This group will appear under "Advanced Topics".
*/
/**
* \page NetworkGuide Network Guide
* \ingroup NetworkTopics
*
* # Network Guide
* Details about networking.
*/
This will create a Advanced Topics tab with Networking Topics as a sub-tab.
By using \defgroup
and \ingroup
, you can fully control how your pages are organized into tabs and sub-tabs in the Doxygen documentation.
In Doxygen, related pages and topics (usually organized using groups) serve different purposes in terms of organizing and displaying documentation. Let's break down the difference between the two:
-
Purpose: Related pages are independent documentation pages that are not tied to specific code elements (like classes, functions, or modules). These pages are often used for high-level documentation such as tutorials, guides, or detailed descriptions of concepts.
-
How They Work: Related pages are created using the
\page
or\mainpage
commands. They exist separately from your code and are generally accessed through a special "Related Pages" section in the Doxygen navigation menu. -
Use Case: These pages are ideal for adding general documentation that doesn't fit directly into the class/module structure of your code. Examples include:
- Installation guides
- Tutorials
- FAQs
- Architectural overviews
-
Example:
/**
* \page InstallationGuide Installation Guide
*
* # How to Install
* This is a detailed guide on how to install the software.
*/
- Where It Appears: Typically, related pages will appear in the "Related Pages" section of the generated documentation.
-
Purpose: Groups (also referred to as topics) allow you to organize code elements (such as classes, files, and functions) into logical sections or categories. These groups create a hierarchical structure in the documentation, where related classes, functions, or pages are grouped together under a specific heading.
-
How They Work: Topics are created using the
\defgroup
command, and you can assign code elements (like classes or functions) or additional pages to these groups using\ingroup
. Groups allow you to organize and document larger, interconnected parts of your codebase. -
Use Case: Topics are typically used for:
- Organizing large codebases into modules (e.g., Networking, File I/O, Math Functions).
- Creating documentation for specific subsystems or features.
- Structuring documentation for code elements that naturally fit into categories.
-
Example:
/**
* \defgroup NetworkModule Network Module
* This module contains all network-related functionality.
*/
/**
* \ingroup NetworkModule
* \class NetworkManager
* Manages network connections and data transfer.
*/
class NetworkManager {};
/**
* \ingroup NetworkModule
* \page NetworkSetup Network Setup
* How to configure the network.
*/
- Where It Appears: Topics (groups) appear as sections in the sidebar navigation of the generated documentation. They typically show up as tabs or categories, and all related code elements (classes, functions, files) are listed under these sections.
Feature | Related Pages | Topics (Groups) |
---|---|---|
Primary Purpose | High-level documentation not tied to code | Organizing code elements into logical categories |
Creation Command |
\page , \mainpage
|
\defgroup , \ingroup
|
Use Case | General guides, tutorials, project overview | Code element categorization (modules, subsystems) |
Hierarchy | Typically standalone | Can be hierarchical (with parent-child groups) |
Content | Non-code specific information (installation, FAQ) | Code elements like classes, functions, and files |
Appearance | In the "Related Pages" section of navigation | In navigation as separate tabs or sections |
-
Related Pages are ideal when you need documentation that stands apart from your codebase, like tutorials, installation instructions, or overviews that aren't closely tied to specific functions or classes.
-
Topics (Groups) are best for structuring the actual code documentation, especially when you want to categorize classes, functions, or modules under logical groupings like "Networking," "UI Components," or "Math Utilities."
By using both related pages and topics, you can create a rich and well-organized documentation structure that covers both high-level and low-level information.
In Doxygen, you can document your code directly in .cpp
files by adding special comment blocks. Doxygen supports various comment styles to explain your functions, classes, variables, and more. Here's how you can properly explain and document your code in .cpp
files.
Doxygen supports several types of comment blocks for documentation. The most commonly used are:
-
C-style block comments:
/** ... */
-
C++-style single-line comments:
///
-
C-style multi-line comments with
/*! ... */
for including documentation in specific places.
You can describe functions, including parameters, return values, exceptions, and more.
/**
* \brief Adds two integers and returns the result.
*
* This function takes two integers as input and returns their sum. It's a simple demonstration of a basic addition operation.
*
* \param a First integer to add.
* \param b Second integer to add.
* \return Sum of the two integers.
* \note This is a very basic function for educational purposes.
*/
int add(int a, int b) {
return a + b;
}
You can explain the purpose of a class, its members, and methods.
/**
* \class Calculator
* \brief A simple calculator class for basic arithmetic operations.
*
* The Calculator class provides methods for performing basic arithmetic operations like addition, subtraction, multiplication, and division.
*/
class Calculator {
public:
/**
* \brief Adds two floating-point numbers.
*
* \param a First number.
* \param b Second number.
* \return The result of the addition.
*/
float add(float a, float b) {
return a + b;
}
/**
* \brief Multiplies two floating-point numbers.
*
* \param a First number.
* \param b Second number.
* \return The result of the multiplication.
*/
float multiply(float a, float b) {
return a * b;
}
};
You can also document individual variables, constants, or macros in your .cpp
file.
/**
* \brief The maximum allowed number of retries.
*
* This constant defines the maximum number of retries for a network operation.
*/
const int MAX_RETRIES = 5;
If you want to provide a detailed explanation of the code logic or the purpose of a block of code, you can use in-line comments with Doxygen tags.
/**
* \brief Computes the factorial of a number.
*
* This function uses a recursive approach to calculate the factorial of a given integer.
* Factorial is defined as:
* - `n! = n * (n-1)!` for n > 0
* - `0! = 1`
*
* \param n The number for which the factorial is to be calculated.
* \return Factorial of the number n.
*/
int factorial(int n) {
if (n == 0) {
return 1; // Base case: factorial of 0 is 1.
}
return n * factorial(n - 1); // Recursive case.
}
If you want to explain a specific part of the code inline, use /*!
or ///
for inline comments.
int sum = 0; ///< This variable holds the cumulative sum.
/// Loop through the array to compute the sum of elements.
for (int i = 0; i < n; ++i) {
sum += array[i]; ///< Add the current element to the sum.
}
Here are some common Doxygen tags you can use to document your code:
-
\brief
– A brief description of the item (function, class, variable, etc.). -
\param
– Used to describe a parameter (e.g.,\param a
). -
\return
– Used to describe the return value of a function. -
\note
– Adds a note for further explanation. -
\warning
– Adds a warning message. -
\todo
– Adds a to-do note for future development. -
\author
– Specifies the author of the code.
/**
* \brief Calculates the power of a number.
*
* This function computes the power of a base number raised to the exponent.
* For example, to calculate 2^3 (2 raised to the power of 3), this function would return 8.
*
* \param base The base number.
* \param exponent The exponent to raise the base number to.
* \return The result of base raised to the power of exponent.
* \throws std::invalid_argument if the exponent is negative.
*/
double power(double base, int exponent) {
if (exponent < 0) {
throw std::invalid_argument("Exponent cannot be negative.");
}
double result = 1;
for (int i = 0; i < exponent; ++i) {
result *= base;
}
return result;
}
After you've added your comments, you can run Doxygen to generate the documentation:
doxygen Doxyfile
This will generate the HTML (or other format) documentation, with the code explanations properly formatted.
By using these techniques, you can fully document your code within the .cpp
files, ensuring that both developers and users of the code understand its functionality and usage.
To create documentation for specific objects (instances) of a class in Doxygen, you can document both the class definition and its member variables (objects). Although Doxygen is primarily designed to document the structure and behavior of classes, functions, and variables, you can still document individual objects (instances) as they are created in the code.
Here's a detailed guide to creating documentation for objects from a class:
First, you should ensure the class itself is documented properly. You can describe the purpose of the class and explain its members.
/**
* \class Car
* \brief A class representing a car object with basic attributes like model, color, and speed.
*
* The Car class represents a basic car with methods to start, stop, and accelerate. It contains member variables
* for storing information about the car's model, color, and speed.
*/
class Car {
public:
/**
* \brief Constructs a Car with the given model and color.
* \param model The model name of the car.
* \param color The color of the car.
*/
Car(const std::string& model, const std::string& color);
/**
* \brief Starts the car.
*/
void start();
/**
* \brief Stops the car.
*/
void stop();
/**
* \brief Accelerates the car by a given amount.
* \param amount The speed increment in km/h.
*/
void accelerate(int amount);
private:
std::string model; ///< The model of the car.
std::string color; ///< The color of the car.
int speed; ///< The current speed of the car in km/h.
};
When you create an instance of this class (an object), you can also document the individual object, especially if it has a specific role in your code.
/**
* \brief The main car object representing John's car.
*
* This object is an instance of the Car class and represents a specific car with the model "Tesla" and color "Red".
*/
Car johnsCar("Tesla", "Red");
/**
* \brief The car used for testing purposes.
*
* This object is used in various tests and represents a black "Audi" with default settings.
*/
Car testCar("Audi", "Black");
You can use the Doxygen comment styles to document objects in a .cpp
file, just like you do with functions and variables.
/**
* \brief The main car object used throughout the program.
*
* This is the car object that will be passed to various functions to demonstrate
* how different car operations work (starting, stopping, accelerating).
*/
Car mainCar("Ford", "Blue");
int main() {
/**
* \brief This is a local car object used only in the main function.
*
* The car object is a "BMW" with a "White" color. It is used temporarily
* for testing the Car class methods.
*/
Car localCar("BMW", "White");
mainCar.start();
mainCar.accelerate(50);
mainCar.stop();
return 0;
}
When documenting objects, you can refer to the class documentation using \ref
or link specific member functions or variables.
/**
* \brief Represents Bob's car, a blue Tesla.
*
* This car uses the methods from the \ref Car class such as \ref Car::start "start()",
* \ref Car::accelerate "accelerate()", and \ref Car::stop "stop()".
*/
Car bobsCar("Tesla", "Blue");
If you have multiple objects from a certain class, you can group them together in your documentation using \defgroup
and \ingroup
for better organization.
/**
* \defgroup CarObjects Instances of Car
* \brief A group of Car objects used in the program.
*
* This group contains several instances of the Car class, each representing a specific car in the program.
* \ingroup Vehicles
*/
/**
* \ingroup CarObjects
* \brief The red Tesla owned by Alice.
*/
Car alicesCar("Tesla", "Red");
/**
* \ingroup CarObjects
* \brief The black BMW used for testing.
*/
Car testBMW("BMW", "Black");
Once you have added the comments, you can run Doxygen to generate the documentation:
doxygen Doxyfile
In the generated documentation, you’ll see:
-
Class documentation: The class (
Car
) will be documented with all its methods and attributes. -
Object documentation: Each object (e.g.,
johnsCar
,mainCar
,localCar
, etc.) will appear in the documentation with the explanations you provided.
- Class Documentation: Always document the class itself, including its member functions and variables.
- Object Documentation: You can document individual objects (instances) in the code to describe their specific purpose or usage.
-
Grouping: Use Doxygen groups (
\defgroup
,\ingroup
) if you want to organize multiple objects in a logical structure. -
References: Use
\ref
to link back to the class or its members when describing specific objects.
By following these steps, you can ensure that both your classes and individual objects are well-documented, making the purpose and functionality of your code clear to future developers and users.
To create a packed HTML documentation that can be opened with just one file, you need to configure Doxygen to generate a single HTML file with all the content embedded. This is usually done using a self-contained HTML file where all the CSS, JavaScript, and images are embedded directly into the file.
-
Modify the Doxyfile Configuration
You need to enable the SINGLE_PAGE_HTML option in the Doxygen configuration file (
Doxyfile
). This option is responsible for generating all documentation into one HTML file. -
Install and Configure the Doxygen Awesome Theme
The default Doxygen output does not support a single HTML file natively. However, using the Doxygen Awesome Theme plugin, you can enable single-page HTML generation. Here's how:
- Download the Doxygen Awesome Theme from its GitHub repository: https://github.com/jothepro/doxygen-awesome-css
- Download the theme's
doxygen-awesome.css
and add it to your project folder (for example, into atheme
directory).
Open your Doxyfile
and modify/add the following options to enable a self-contained HTML file:
-
Set custom CSS file: Find and set the following option in your Doxyfile to include the custom CSS (assuming you placed it in a
theme
directory):HTML_EXTRA_STYLESHEET = theme/doxygen-awesome.css
-
Enable single-page HTML: Add the following option to enable the single-page HTML feature of the Doxygen Awesome theme:
GENERATE_SINGLE_PAGE = YES
-
Enable embedded resources: Set the
HTML_TIMESTAMP
option toNO
to avoid cache issues, and to make the output more portable:HTML_TIMESTAMP = NO
If you are using the latest version of the theme, it might embed images, scripts, and styles directly into the HTML file.
After configuring the Doxyfile, run Doxygen to generate the documentation:
doxygen Doxyfile
Once Doxygen finishes, it will generate a single HTML file that contains all the documentation. You can open this file in any web browser, and it will contain all the styles, scripts, and content without needing external assets.
- Single Page Documentation Limitation: While this approach allows you to have a single file, bear in mind that extremely large projects may result in a large HTML file, which might affect performance when rendering in a browser.
- Alternatives: If your project is large, consider using tools like Sphinx or other documentation generators that also support single-page HTML outputs.
By following these steps, you'll be able to generate a single-file HTML documentation that can be easily shared and opened without needing additional assets.