cpp-api-documentation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Documentation

API文档

1. Benefits

1. 优势

  • Discoverability
    Well-documented APIs enable developers to quickly understand and use components without reading implementation details.
  • Maintainability
    Documentation embedded in source code stays synchronized with implementation, reducing drift between code and documentation.
  • Traceability
    Documentation comments serve as living specifications, keeping API contracts synchronized with implementation.
  • 可发现性
    文档完善的API能让开发者无需阅读实现细节,就能快速理解并使用组件。
  • 可维护性
    嵌入在源代码中的文档会与实现保持同步,减少代码与文档之间的偏差。
  • 可追溯性
    文档注释可作为动态规范,确保API契约与实现保持同步。

2. Principles

2. 原则

Effective API documentation follows these core principles.
  • Complete
    Document all public APIs including classes, functions, parameters, return values, and exceptions. Private implementation details may be omitted.
  • Contextual
    Documentation provides context about usage patterns, performance characteristics, and thread safety guarantees.
  • Consistent
    Use a uniform style, format, terminology and structure throughout the API documentation using the patterns defined in this skill.
  • Concise
    Use clear, brief descriptions. Avoid redundant information that restates what is obvious from the signature.
  • Concrete
    Provide specific details about behavior, edge cases, and error conditions rather than vague statements.
  • Convenient
    Documentation should be easy to access and navigate, integrated with development tools and workflows.
  • Accurate
    Documentation must match the actual behavior. Update documentation whenever the implementation changes.
  • Actionable
    Include usage examples, preconditions, postconditions, and error handling to help developers use the API correctly.
有效的API文档遵循以下核心原则。
  • 完整性
    记录所有公开API,包括类、函数、参数、返回值和异常。可省略私有实现细节。
  • 关联性
    文档需提供使用模式、性能特性和线程安全保证等相关上下文信息。
  • 一致性
    遵循本技能中定义的模式,在整个API文档中使用统一的风格、格式、术语和结构。
  • 简洁性
    使用清晰、简洁的描述。避免重复从签名中就能明显看出的信息。
  • 具体性
    提供有关行为、边界情况和错误条件的具体细节,而非模糊表述。
  • 易用性
    文档应易于访问和导航,并与开发工具和工作流集成。
  • 准确性
    文档必须与实际行为相符。每次实现变更时都要更新文档。
  • 实用性
    包含使用示例、前置条件、后置条件和错误处理说明,帮助开发者正确使用API。

3. Patterns

3. 模式

3.1. File Documentation

3.1. 文件文档

File-level documentation provides context for the entire header file.
  • Purpose
    Describes the file's role in the project architecture.
  • Author
    Identifies the original author(s) of the file.
  • License
    Specifies the licensing terms (typically SPDX identifier).
文件级文档为整个头文件提供上下文信息。
  • 用途
    描述文件在项目架构中的作用。
  • 作者
    标识文件的原始作者。
  • 许可证
    指定许可条款(通常为SPDX标识符)。

3.2. Namespace Documentation

3.2. 命名空间文档

Namespace-level documentation describes the purpose of the namespace.
  • Brief
    A one-line summary of what the namespace contains.
  • Details
    Extended description of the namespace's role and contents.
命名空间级文档描述命名空间的用途。
  • 简介
    一行总结命名空间包含的内容。
  • 详情
    对命名空间的作用和内容的扩展描述。

3.3. Class Documentation

3.3. 类文档

Class-level documentation describes the abstraction.
  • Brief
    A one-line summary of what the class represents.
  • Details
    Extended description of responsibilities, invariants, and usage patterns.
  • Template Parameters
    For template classes, document each template parameter's purpose and constraints.
类级文档描述抽象概念。
  • 简介
    一行总结类的代表含义。
  • 详情
    对职责、不变量和使用模式的扩展描述。
  • 模板参数
    对于模板类,记录每个模板参数的用途和约束条件。

3.4. Function/Method Documentation

3.4. 函数/方法文档

Function-level documentation describes the contract.
  • Brief
    A one-line summary of what the function does.
  • Parameters
    Document each parameter with
    @param
    including direction (
    [in]
    ,
    [out]
    ,
    [in,out]
    ).
  • Return Value
    Document the return value with
    @return
    or
    @retval
    for specific values.
  • Exceptions
    Document thrown exceptions with
    @throws
    or
    @exception
    .
  • Warnings
    Use
    @warning
    for critical warnings about misuse.
  • Notes
    Use
    @note
    for important information.
  • Preconditions
    Document preconditions with
    @pre
    .
  • Postconditions
    Document postconditions with
    @post
    .
  • Code Examples
    Use
    @code
    and
    @endcode
    blocks for usage examples.
函数级文档描述契约。
  • 简介
    一行总结函数的功能。
  • 参数
    使用
    @param
    记录每个参数,包括方向(
    [in]
    [out]
    [in,out]
    )。
  • 返回值
    使用
    @return
    @retval
    (针对特定值)记录返回值。
  • 异常
    使用
    @throws
    @exception
    记录抛出的异常。
  • 警告
    使用
    @warning
    记录有关误用的严重警告。
  • 说明
    使用
    @note
    记录重要信息。
  • 前置条件
    使用
    @pre
    记录前置条件。
  • 后置条件
    使用
    @post
    记录后置条件。
  • 代码示例
    使用
    @code
    @endcode
    块添加使用示例。

3.5. Cross-References

3.5. 交叉引用

Cross-references link related documentation.
  • See Also
    Use
    @see
    to reference related functions, classes, or external resources.
交叉引用链接相关文档。
  • 另请参阅
    使用
    @see
    引用相关函数、类或外部资源。

3.6. Member Documentation

3.6. 成员文档

Member-level documentation clarifies data semantics.
  • Inline Comments
    Use
    ///< description
    for trailing inline documentation.
  • Block Comments
    Use
    /// description
    for preceding documentation.
成员级文档阐明数据语义。
  • 行内注释
    使用
    ///< description
    添加尾随行内文档。
  • 块注释
    使用
    /// description
    添加前置文档。

3.7. Enumerations

3.7. 枚举

Enumerations document possible values and their meanings.
  • Values
    Document each enumerator with a brief Inline Comments description.
枚举记录可能的值及其含义。
  • 使用行内注释为每个枚举值添加简短描述。

3.8. Grouping and Modules

3.8. 分组与模块

Organize related elements into logical groups.
  • Defgroups
    Use
    @defgroup
    to create named documentation modules.
  • Ingroups
    Use
    @ingroup
    to add elements to existing groups.
  • Memberof
    Use
    @memberof
    for explicit class membership.
将相关元素组织为逻辑组。
  • 定义组
    使用
    @defgroup
    创建命名文档模块。
  • 加入组
    使用
    @ingroup
    将元素添加到现有组中。
  • 成员归属
    使用
    @memberof
    明确类成员归属。

3.9. Inheritance

3.9. 继承

Class hierarchies and inherited documentation.
  • Base Classes
    Document inherited classes with
    @copydoc
    or
    @copybrief
    to reuse base class documentation.
类层次结构和继承的文档。
  • 基类
    使用
    @copydoc
    @copybrief
    记录继承的类,以复用基类文档。

3.10. Formula Documentation

3.10. 公式文档

Mathematical formulas using LaTeX syntax for algorithms and technical documentation.
  • Inline Formulas
    Use
    \f$..\f$
    for formulas that appear within running text (opens LaTeX math mode).
  • Inline Text-Mode Formulas
    Use
    \f(...\f)
    for LaTeX elements that don't require explicit math mode (e.g., logos like
    \LaTeX
    ).
  • Displayed Formulas
    Use
    \f[...\f]
    for centered, unnumbered equations on separate lines.
  • Environment Formulas
    Use
    \f{environment}{...\f}
    for specific LaTeX environments (e.g.,
    eqnarray*
    ,
    align
    ).
  • MathJax Alternative
    Enable
    USE_MATHJAX
    in Doxyfile for client-side formula rendering without requiring LaTeX installation.
  • Custom Macros
    Use
    FORMULA_MACROFILE
    configuration to define reusable LaTeX commands with
    \newcommand
    .
使用LaTeX语法编写算法和技术文档中的数学公式。
  • 行内公式
    使用
    \f$..\f$
    表示嵌入在正文中的公式(开启LaTeX数学模式)。
  • 行内文本模式公式
    使用
    \f(...\f)
    表示不需要显式数学模式的LaTeX元素(例如
    \LaTeX
    等标识)。
  • 显示公式
    使用
    \f[...\f]
    表示单独一行居中显示的无编号方程。
  • 环境公式
    使用
    \f{environment}{...\f}
    表示特定的LaTeX环境(例如
    eqnarray*
    align
    )。
  • MathJax替代方案
    在Doxyfile中启用
    USE_MATHJAX
    ,无需安装LaTeX即可在客户端渲染公式。
  • 自定义宏
    使用
    FORMULA_MACROFILE
    配置,通过
    \newcommand
    定义可复用的LaTeX命令。

4. Workflow

4. 工作流程

[!IMPORTANT] Do NOT create Doxyfile, scripts, or other resource files. Only modify header files.
  1. Identify
    Identify undocumented or poorly documented public APIs in header files (e.g.,
    src/<module>/<header>.hpp
    ).
  2. Add Documentation Comments
    Add Doxygen-compatible documentation comments directly to header files following the templates below.
  3. Documentation Coverage Requirements
    Include comprehensive documentation for:
    • All public classes, structs, and enums
    • All public and protected member functions
    • All function parameters and return values
    • All template parameters
    • Exception specifications
    • Thread safety guarantees when applicable
    • Complexity guarantees for algorithms
  4. Apply Templates
    Structure all documentation using the template patterns below.
  5. Review
    Review documentation for accuracy and readability.
[!IMPORTANT] 请勿创建Doxyfile、脚本或其他资源文件。仅修改头文件。
  1. 识别
    识别头文件中未编写文档或文档不完善的公开API(例如
    src/<module>/<header>.hpp
    )。
  2. 添加文档注释
    按照以下模板,直接在头文件中添加兼容Doxygen的文档注释。
  3. 文档覆盖要求
    需包含全面的文档内容:
    • 所有公开类、结构体和枚举
    • 所有公开和受保护的成员函数
    • 所有函数参数和返回值
    • 所有模板参数
    • 异常说明
    • 适用时的线程安全保证
    • 算法的复杂度保证
  4. 应用模板
    使用以下模板模式构建所有文档。
  5. 审核
    审核文档的准确性和可读性。

5. Style Guide

5. 风格指南

Doxygen supports multiple comment styles. Use the Javadoc style for consistency.
  • Language
    Write documentation in clear, concise English. Use present tense for descriptions ("Returns the sum" not "Will return the sum").
  • Line Length
    Keep documentation lines under 100 characters for readability.
  • Block Comments
    Use
    /** ... */
    for multi-line documentation blocks. Each line within the block should start with
    *
    .
  • Comment Style
    Prefer
    ///
    for single-line documentation and
    /** */
    for multi-line documentation blocks. Use Javadoc-style commands (
    @param
    ,
    @return
    ) rather than Qt-style (
    \param
    ,
    \return
    ).
  • Brief Descriptions
    Use
    @brief
    for explicit brief descriptions.
  • Detailed Descriptions
    Add detailed descriptions after the brief, separated by a blank line or using
    @details
    .
  • Parameter Direction
    Always specify parameter direction using
    [in]
    ,
    [out]
    , or
    [in,out]
    for clarity.
  • Code Examples
    Use
    @code
    and
    @endcode
    blocks for usage examples within documentation.
  • Cross-References
    Use
    @see
    to reference related functions, classes, or external resources.
  • Warnings and Notes
    Use
    @note
    for important information and
    @warning
    for critical warnings.
  • Deprecation
    Mark deprecated APIs with
    @deprecated
    including migration guidance.
  • TODO Items
    Use
    @todo
    for planned improvements visible in generated documentation.
  • Order of Tags
    Follow this order for function documentation:
    1. @brief
    2. @details
      (if needed)
    3. @tparam
      (for templates)
    4. @param
    5. @return
    6. @throws
    7. @pre
    8. @post
    9. @note
    10. @warning
    11. @see
    12. @deprecated
Doxygen支持多种注释风格。为保持一致性,使用Javadoc风格。
  • 语言
    使用清晰、简洁的英文编写文档。描述使用一般现在时(例如“返回总和”而非“将返回总和”)。
  • 行长度
    文档行长度保持在100字符以内,以保证可读性。
  • 块注释
    使用
    /** ... */
    编写多行文档块。块内每行以
    *
    开头。
  • 注释风格
    单行文档优先使用
    ///
    ,多行文档块优先使用
    /** */
    。使用Javadoc风格的命令(
    @param
    @return
    )而非Qt风格(
    \param
    \return
    )。
  • 简介描述
    使用
    @brief
    添加明确的简介描述。
  • 详细描述
    在简介后添加详细描述,可通过空行分隔或使用
    @details
  • 参数方向
    始终使用
    [in]
    [out]
    [in,out]
    指定参数方向,确保清晰。
  • 代码示例
    在文档中使用
    @code
    @endcode
    块添加使用示例。
  • 交叉引用
    使用
    @see
    引用相关函数、类或外部资源。
  • 警告与说明
    使用
    @note
    记录重要信息,使用
    @warning
    记录严重警告。
  • 弃用标识
    使用
    @deprecated
    标记已弃用的API,并提供迁移指导。
  • TODO项
    使用
    @todo
    记录计划中的改进,这些内容会在生成的文档中显示。
  • 标签顺序
    函数文档遵循以下标签顺序:
    1. @brief
    2. @details
      (如需)
    3. @tparam
      (针对模板)
    4. @param
    5. @return
    6. @throws
    7. @pre
    8. @post
    9. @note
    10. @warning
    11. @see
    12. @deprecated

6. Template

6. 模板

Use these templates for new documentation. Replace placeholders with actual values.
使用以下模板编写新文档。将占位符替换为实际值。

6.1. File Header Template

6.1. 文件头模板

[!NOTE] Place the
@file
block after the include guard (
#pragma once
or
#ifndef
/
#define
). This ensures the documentation is parsed once along with the declarations it describes and keeps preprocessor directives separate from API documentation.
cpp
#pragma once

/**
 * @file <filename>.hpp
 * @brief One-line description of the file's purpose.
 *
 * Detailed description of the file's contents and design decisions.
 *
 * @author <author_name>
 * @copyright Copyright (c) <year> <organization>
 * @license SPDX-License-Identifier: <license_identifier>
 */
[!NOTE] 将
@file
块放在包含保护(
#pragma once
#ifndef
/
#define
之后。这样能确保文档与它所描述的声明一起被解析一次,并将预处理器指令与API文档分开。
cpp
#pragma once

/**
 * @file <filename>.hpp
 * @brief 一行描述文件的用途。
 *
 * 详细描述文件的内容和设计决策。
 *
 * @author <author_name>
 * @copyright Copyright (c) <year> <organization>
 * @license SPDX-License-Identifier: <license_identifier>
 */

6.2. Namespace Template

6.2. 命名空间模板

cpp
/**
 * @brief One-line description of namespace contents.
 *
 * Detailed description of the namespace's role, the types of
 * components it contains, and how they relate to each other.
 */
namespace namespace_name {

// Namespace contents

}  // namespace namespace_name
cpp
/**
 * @brief 一行描述命名空间的内容。
 *
 * 详细描述命名空间的作用、包含的组件类型以及它们之间的关系。
 */
namespace namespace_name {

// 命名空间内容

}  // namespace namespace_name

6.3. Class Template

6.3. 类模板

cpp
/**
 * @brief One-line description of the class.
 *
 * Detailed description of the class responsibility, key invariants,
 * and usage patterns.
 *
 * @tparam T Description of template parameter and constraints.
 *
 * @note Thread safety: Describe thread safety guarantees.
 *
 * @see RelatedClass
 *
 * @code
 * ClassName<int> obj;
 * obj.method(param);
 * @endcode
 */
template <typename T>
class ClassName
{
  // ...
};
cpp
/**
 * @brief 一行描述类的含义。
 *
 * 详细描述类的职责、关键不变量和使用模式。
 *
 * @tparam T 模板参数的描述和约束条件。
 *
 * @note 线程安全:描述线程安全保证。
 *
 * @see RelatedClass
 *
 * @code
 * ClassName<int> obj;
 * obj.method(param);
 * @endcode
 */
template <typename T>
class ClassName
{
  // ...
};

6.4. Function Template

6.4. 函数模板

cpp
/**
 * @brief One-line description of what the function does.
 *
 * Detailed description including algorithm details and edge cases.
 *
 * @param[in] param1 Description of the input parameter.
 * @param[out] param2 Description of the output parameter.
 * @param[in,out] param3 Description of bidirectional parameter.
 *
 * @return Description of the return value.
 * @retval specific_value Meaning of this specific return value.
 *
 * @throws std::invalid_argument If param1 is invalid.
 * @throws std::runtime_error If operation fails.
 *
 * @pre Preconditions that must be met before calling.
 * @post Postconditions guaranteed after successful execution.
 *
 * @note Important information for users.
 * @warning Critical warnings about potential misuse.
 *
 * @see relatedFunction()
 *
 * @code
 * auto result = functionName(input, output);
 * @endcode
 */
ReturnType functionName(const InputType& param1, OutputType& param2);
cpp
/**
 * @brief 一行描述函数的功能。
 *
 * 详细描述包括算法细节和边界情况。
 *
 * @param[in] param1 输入参数的描述。
 * @param[out] param2 输出参数的描述。
 * @param[in,out] param3 双向参数的描述。
 *
 * @return 返回值的描述。
 * @retval specific_value 该特定返回值的含义。
 *
 * @throws std::invalid_argument 如果param1无效。
 * @throws std::runtime_error 如果操作失败。
 *
 * @pre 调用前必须满足的前置条件。
 * @post 执行成功后保证满足的后置条件。
 *
 * @note 给用户的重要信息。
 * @warning 有关潜在误用的严重警告。
 *
 * @see relatedFunction()
 *
 * @code
 * auto result = functionName(input, output);
 * @endcode
 */
ReturnType functionName(const InputType& param1, OutputType& param2);

6.5. Member Variable Template

6.5. 成员变量模板

cpp
class ClassName
{
private:
  int count_;       ///< Number of items currently stored.
  bool is_valid_;   ///< Whether the object is in a valid state.

  /// Description for simple members.
  int simple_member_;

  /**
   * @brief Buffer for temporary storage.
   *
   * Detailed explanation of the member's purpose and
   * synchronization requirements.
   */
  std::vector<char> buffer_;
};
cpp
class ClassName
{
private:
  int count_;       ///< 当前存储的项目数量。
  bool is_valid_;   ///< 对象是否处于有效状态。

  /// 简单成员的描述。
  int simple_member_;

  /**
   * @brief 临时存储的缓冲区。
   *
   * 详细说明成员的用途和同步要求。
   */
  std::vector<char> buffer_;
};

6.6. Enumeration Template

6.6. 枚举模板

cpp
/**
 * @brief Description of what this enumeration represents.
 *
 * Detailed description of the enum's purpose and usage context.
 */
enum class EnumName
{
  Success,     ///< Operation completed successfully.
  Error,       ///< Operation failed with an error.
  Pending,     ///< Operation is still in progress.
  NotFound     ///< Requested item was not found.
};
cpp
/**
 * @brief 此枚举代表的含义。
 *
 * 详细描述枚举的用途和使用上下文。
 */
enum class EnumName
{
  Success,     ///< 操作成功完成。
  Error,       ///< 操作执行失败并报错。
  Pending,     ///< 操作仍在进行中。
  NotFound     ///< 未找到请求的项目。
};

6.7. Module/Group Template

6.7. 模块/分组模板

cpp
/**
 * @defgroup module_name Module Display Name
 * @brief One-line description of the module.
 *
 * Detailed description of the module purpose and components.
 *
 * @{
 */

// Classes and functions belonging to this group

/** @} */  // End of module_name
cpp
/**
 * @defgroup module_name 模块显示名称
 * @brief 一行描述模块的用途。
 *
 * 详细描述模块的用途和组件。
 *
 * @{
 */

// 属于此组的类和函数

/** @} */  // End of module_name

6.8. Formula Template

6.8. 公式模板

cpp
/**
 * @brief Calculates the Euclidean distance between two points.
 *
 * The distance between \f$(x_1,y_1)\f$ and \f$(x_2,y_2)\f$ is
 * \f$\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}\f$.
 *
 * For complex equations, use displayed formulas:
 * \f[
 *   d = \sqrt{\sum_{i=1}^{n}(p_i - q_i)^2}
 * \f]
 *
 * Multi-line equations using eqnarray environment:
 * \f{eqnarray*}{
 *   E &=& mc^2 \\
 *   F &=& ma
 * \f}
 *
 * @param[in] x1 X-coordinate of the first point.
 * @param[in] y1 Y-coordinate of the first point.
 * @param[in] x2 X-coordinate of the second point.
 * @param[in] y2 Y-coordinate of the second point.
 *
 * @return The Euclidean distance \f$d \geq 0\f$.
 */
double distance(double x1, double y1, double x2, double y2);
cpp
/**
 * @brief 计算两点之间的欧几里得距离。
 *
 * \f$(x_1,y_1)\f$和\f$(x_2,y_2)\f$之间的距离为
 * \f$\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}\f$。
 *
 * 对于复杂方程,使用显示公式:
 * \f[
 *   d = \sqrt{\sum_{i=1}^{n}(p_i - q_i)^2}
 * \f]
 *
 * 使用eqnarray环境编写多行方程:
 * \f{eqnarray*}{
 *   E &=& mc^2 \\
 *   F &=& ma
 * \f}
 *
 * @param[in] x1 第一个点的X坐标。
 * @param[in] y1 第一个点的Y坐标。
 * @param[in] x2 第二个点的X坐标。
 * @param[in] y2 第二个点的Y坐标。
 *
 * @return 欧几里得距离\f$d \geq 0\f$。
 */
double distance(double x1, double y1, double x2, double y2);

7. References

7. 参考资料