cpp-api-documentation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Documentation
API文档
Instructions for AI coding agents on adding Doxygen-compatible documentation comments to C++ header files.
[!NOTE] This skill is for documenting header files only. Do NOT create new resource files (e.g., Doxyfile, scripts, README).
AI编码代理为C++头文件添加兼容Doxygen的文档注释的操作指南。
[!NOTE] 本技能仅用于为头文件编写文档。请勿创建Doxyfile、脚本、README等新资源文件。
1. Benefits
1. 优势
-
DiscoverabilityWell-documented APIs enable developers to quickly understand and use components without reading implementation details.
-
MaintainabilityDocumentation embedded in source code stays synchronized with implementation, reducing drift between code and documentation.
-
TraceabilityDocumentation comments serve as living specifications, keeping API contracts synchronized with implementation.
-
可发现性文档完善的API能让开发者无需阅读实现细节,就能快速理解并使用组件。
-
可维护性嵌入在源代码中的文档会与实现保持同步,减少代码与文档之间的偏差。
-
可追溯性文档注释可作为动态规范,确保API契约与实现保持同步。
2. Principles
2. 原则
Effective API documentation follows these core principles.
-
CompleteDocument all public APIs including classes, functions, parameters, return values, and exceptions. Private implementation details may be omitted.
-
ContextualDocumentation provides context about usage patterns, performance characteristics, and thread safety guarantees.
-
ConsistentUse a uniform style, format, terminology and structure throughout the API documentation using the patterns defined in this skill.
-
ConciseUse clear, brief descriptions. Avoid redundant information that restates what is obvious from the signature.
-
ConcreteProvide specific details about behavior, edge cases, and error conditions rather than vague statements.
-
ConvenientDocumentation should be easy to access and navigate, integrated with development tools and workflows.
-
AccurateDocumentation must match the actual behavior. Update documentation whenever the implementation changes.
-
ActionableInclude 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.
-
PurposeDescribes the file's role in the project architecture.
-
AuthorIdentifies the original author(s) of the file.
-
LicenseSpecifies the licensing terms (typically SPDX identifier).
文件级文档为整个头文件提供上下文信息。
-
用途描述文件在项目架构中的作用。
-
作者标识文件的原始作者。
-
许可证指定许可条款(通常为SPDX标识符)。
3.2. Namespace Documentation
3.2. 命名空间文档
Namespace-level documentation describes the purpose of the namespace.
-
BriefA one-line summary of what the namespace contains.
-
DetailsExtended description of the namespace's role and contents.
命名空间级文档描述命名空间的用途。
-
简介一行总结命名空间包含的内容。
-
详情对命名空间的作用和内容的扩展描述。
3.3. Class Documentation
3.3. 类文档
Class-level documentation describes the abstraction.
-
BriefA one-line summary of what the class represents.
-
DetailsExtended description of responsibilities, invariants, and usage patterns.
-
Template ParametersFor template classes, document each template parameter's purpose and constraints.
类级文档描述抽象概念。
-
简介一行总结类的代表含义。
-
详情对职责、不变量和使用模式的扩展描述。
-
模板参数对于模板类,记录每个模板参数的用途和约束条件。
3.4. Function/Method Documentation
3.4. 函数/方法文档
Function-level documentation describes the contract.
-
BriefA one-line summary of what the function does.
-
ParametersDocument each parameter withincluding direction (
@param,[in],[out]).[in,out] -
Return ValueDocument the return value withor
@returnfor specific values.@retval -
ExceptionsDocument thrown exceptions withor
@throws.@exception -
WarningsUsefor critical warnings about misuse.
@warning -
NotesUsefor important information.
@note -
PreconditionsDocument preconditions with.
@pre -
PostconditionsDocument postconditions with.
@post -
Code ExamplesUseand
@codeblocks for usage examples.@endcode
函数级文档描述契约。
-
简介一行总结函数的功能。
-
参数使用记录每个参数,包括方向(
@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
Useto reference related functions, classes, or external resources.
@see
交叉引用链接相关文档。
- 另请参阅
使用引用相关函数、类或外部资源。
@see
3.6. Member Documentation
3.6. 成员文档
Member-level documentation clarifies data semantics.
-
Inline CommentsUsefor trailing inline documentation.
///< description -
Block CommentsUsefor preceding documentation.
/// description
成员级文档阐明数据语义。
-
行内注释使用添加尾随行内文档。
///< 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.
-
DefgroupsUseto create named documentation modules.
@defgroup -
IngroupsUseto add elements to existing groups.
@ingroup -
MemberofUsefor explicit class membership.
@memberof
将相关元素组织为逻辑组。
-
定义组使用创建命名文档模块。
@defgroup -
加入组使用将元素添加到现有组中。
@ingroup -
成员归属使用明确类成员归属。
@memberof
3.9. Inheritance
3.9. 继承
Class hierarchies and inherited documentation.
- Base Classes
Document inherited classes withor
@copydocto reuse base class documentation.@copybrief
类层次结构和继承的文档。
- 基类
使用或
@copydoc记录继承的类,以复用基类文档。@copybrief
3.10. Formula Documentation
3.10. 公式文档
Mathematical formulas using LaTeX syntax for algorithms and technical documentation.
-
Inline FormulasUsefor formulas that appear within running text (opens LaTeX math mode).
\f$..\f$ -
Inline Text-Mode FormulasUsefor LaTeX elements that don't require explicit math mode (e.g., logos like
\f(...\f)).\LaTeX -
Displayed FormulasUsefor centered, unnumbered equations on separate lines.
\f[...\f] -
Environment FormulasUsefor specific LaTeX environments (e.g.,
\f{environment}{...\f},eqnarray*).align -
MathJax AlternativeEnablein Doxyfile for client-side formula rendering without requiring LaTeX installation.
USE_MATHJAX -
Custom MacrosUseconfiguration to define reusable LaTeX commands with
FORMULA_MACROFILE.\newcommand
使用LaTeX语法编写算法和技术文档中的数学公式。
-
行内公式使用表示嵌入在正文中的公式(开启LaTeX数学模式)。
\f$..\f$ -
行内文本模式公式使用表示不需要显式数学模式的LaTeX元素(例如
\f(...\f)等标识)。\LaTeX -
显示公式使用表示单独一行居中显示的无编号方程。
\f[...\f] -
环境公式使用表示特定的LaTeX环境(例如
\f{environment}{...\f}、eqnarray*)。align -
MathJax替代方案在Doxyfile中启用,无需安装LaTeX即可在客户端渲染公式。
USE_MATHJAX -
自定义宏使用配置,通过
FORMULA_MACROFILE定义可复用的LaTeX命令。\newcommand
4. Workflow
4. 工作流程
[!IMPORTANT] Do NOT create Doxyfile, scripts, or other resource files. Only modify header files.
-
IdentifyIdentify undocumented or poorly documented public APIs in header files (e.g.,).
src/<module>/<header>.hpp -
Add Documentation CommentsAdd Doxygen-compatible documentation comments directly to header files following the templates below.
-
Documentation Coverage RequirementsInclude 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
-
Apply TemplatesStructure all documentation using the template patterns below.
-
ReviewReview documentation for accuracy and readability.
[!IMPORTANT] 请勿创建Doxyfile、脚本或其他资源文件。仅修改头文件。
-
识别识别头文件中未编写文档或文档不完善的公开API(例如)。
src/<module>/<header>.hpp -
添加文档注释按照以下模板,直接在头文件中添加兼容Doxygen的文档注释。
-
文档覆盖要求需包含全面的文档内容:
- 所有公开类、结构体和枚举
- 所有公开和受保护的成员函数
- 所有函数参数和返回值
- 所有模板参数
- 异常说明
- 适用时的线程安全保证
- 算法的复杂度保证
-
应用模板使用以下模板模式构建所有文档。
-
审核审核文档的准确性和可读性。
5. Style Guide
5. 风格指南
Doxygen supports multiple comment styles. Use the Javadoc style for consistency.
-
LanguageWrite documentation in clear, concise English. Use present tense for descriptions ("Returns the sum" not "Will return the sum").
-
Line LengthKeep documentation lines under 100 characters for readability.
-
Block CommentsUsefor multi-line documentation blocks. Each line within the block should start with
/** ... */.* -
Comment StylePreferfor single-line documentation and
///for multi-line documentation blocks. Use Javadoc-style commands (/** */,@param) rather than Qt-style (@return,\param).\return -
Brief DescriptionsUsefor explicit brief descriptions.
@brief -
Detailed DescriptionsAdd detailed descriptions after the brief, separated by a blank line or using.
@details -
Parameter DirectionAlways specify parameter direction using,
[in], or[out]for clarity.[in,out] -
Code ExamplesUseand
@codeblocks for usage examples within documentation.@endcode -
Cross-ReferencesUseto reference related functions, classes, or external resources.
@see -
Warnings and NotesUsefor important information and
@notefor critical warnings.@warning -
DeprecationMark deprecated APIs withincluding migration guidance.
@deprecated -
TODO ItemsUsefor planned improvements visible in generated documentation.
@todo -
Order of TagsFollow this order for function documentation:
@brief- (if needed)
@details - (for templates)
@tparam @param@return@throws@pre@post@note@warning@see@deprecated
Doxygen支持多种注释风格。为保持一致性,使用Javadoc风格。
-
语言使用清晰、简洁的英文编写文档。描述使用一般现在时(例如“返回总和”而非“将返回总和”)。
-
行长度文档行长度保持在100字符以内,以保证可读性。
-
块注释使用编写多行文档块。块内每行以
/** ... */开头。* -
注释风格单行文档优先使用,多行文档块优先使用
///。使用Javadoc风格的命令(/** */、@param)而非Qt风格(@return、\param)。\return -
简介描述使用添加明确的简介描述。
@brief -
详细描述在简介后添加详细描述,可通过空行分隔或使用。
@details -
参数方向始终使用、
[in]或[out]指定参数方向,确保清晰。[in,out] -
代码示例在文档中使用和
@code块添加使用示例。@endcode -
交叉引用使用引用相关函数、类或外部资源。
@see -
警告与说明使用记录重要信息,使用
@note记录严重警告。@warning -
弃用标识使用标记已弃用的API,并提供迁移指导。
@deprecated -
TODO项使用记录计划中的改进,这些内容会在生成的文档中显示。
@todo -
标签顺序函数文档遵循以下标签顺序:
@brief- (如需)
@details - (针对模板)
@tparam @param@return@throws@pre@post@note@warning@see@deprecated
6. Template
6. 模板
Use these templates for new documentation. Replace placeholders with actual values.
使用以下模板编写新文档。将占位符替换为实际值。
6.1. File Header Template
6.1. 文件头模板
[!NOTE] Place theblock after the include guard (@fileor#pragma once/#ifndef). This ensures the documentation is parsed once along with the declarations it describes and keeps preprocessor directives separate from API documentation.#define
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)之后。这样能确保文档与它所描述的声明一起被解析一次,并将预处理器指令与API文档分开。#define
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_namecpp
/**
* @brief 一行描述命名空间的内容。
*
* 详细描述命名空间的作用、包含的组件类型以及它们之间的关系。
*/
namespace namespace_name {
// 命名空间内容
} // namespace namespace_name6.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_namecpp
/**
* @defgroup module_name 模块显示名称
* @brief 一行描述模块的用途。
*
* 详细描述模块的用途和组件。
*
* @{
*/
// 属于此组的类和函数
/** @} */ // End of module_name6.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);