home / skills / openharmonyinsight / openharmony-skills / cpp-include-sorter

cpp-include-sorter skill

/skills/cpp-include-sorter

This skill automatically sorts C/C++ #include statements, preserving conditional blocks and grouping corresponding, system, and local headers for clean,

npx playbooks add skill openharmonyinsight/openharmony-skills --skill cpp-include-sorter

Review the files below or copy the command above to add this skill to your agents.

Files (2)
SKILL.md
3.5 KB
---
name: cpp-include-sorter
description: Automatically sorts C/C++ header files (#include statements) with full support for conditional compilation blocks. Use when Claude needs to organize #include statements in .cpp/.h files. Handles: (1) Corresponding header placement first (e.g., file.cpp includes file.h), (2) System headers (<>) sorted alphabetically, (3) Local headers ("") sorted alphabetically, (4) Conditional compilation blocks (#ifdef/#ifndef/#if defined) where headers participate in global sort while preserving block structure. Key features: prefers longer paths for duplicate includes, preserves inline/preceding comments, handles #elif/#else blocks, validates no headers are lost.
---

# C/C++ Include Sorter

Automatically sorts `#include` statements in C/C++ source files with intelligent handling of conditional compilation blocks.

## Quick Start

Sort all `.cpp` files in a directory:

```bash
python scripts/sort_includes.py <directory-path>
```

Preview changes without modifying files:

```bash
python scripts/sort_includes.py <directory-path> --dry-run
```

## Sorting Rules

Includes are organized into **3 categories** with blank lines between each group:

1. **Corresponding header** - For `file.cpp`, `file.h` is placed first (prefers longest path if duplicates exist)
2. **System headers** - Headers with angle brackets `<>` (sorted alphabetically)
3. **Local headers** - Headers with double quotes `""` (sorted alphabetically)

### Conditional Compilation Blocks

`#ifdef`/`#ifndef`/`#if defined` blocks are treated as units:

- Blocks participate in global sorting based on their first include
- Headers **inside** each block are also sorted (system headers first, then local headers)
- Block structure (`#ifdef`...`#endif`) is preserved
- `#elif` and `#else` blocks are supported

## Example

**Before:**
```cpp
#include "common/rs_log.h"
#include "rs_trace.h"
#include <memory>
#ifdef RS_ENABLE_GPU
#include "feature/uifirst/rs_sub_thread_manager.h"
#include "feature/capture/rs_ui_capture_task_parallel.h"
#endif
#include "platform/common/rs_system_properties.h"
```

**After:**
```cpp
#include "rs_trace.h"        // 1. Corresponding header (longest path preferred)

#include <memory>             // 2. System headers (alphabetical)

#include "common/rs_log.h"    // 3. Local headers (alphabetical)
#ifdef RS_ENABLE_GPU
#include "feature/capture/rs_ui_capture_task_parallel.h"
#include "feature/uifirst/rs_sub_thread_manager.h"
#endif
#include "platform/common/rs_system_properties.h"
```

## Features

- **Duplicate include handling**: When multiple includes with same filename but different paths exist (e.g., `"file.h"` and `"path/to/file.h"`), the longest path is used as the corresponding header and placed first
- **Comment preservation**: Inline comments (`// comment`) and preceding comments are preserved
- **Nested conditional blocks**: Handles `#elif` and `#else` within `#ifdef` blocks
- **Validation**: Verifies no headers are lost during sorting

## Script Reference

See `scripts/sort_includes.py` for implementation details.

Key functions:
- `extract_includes_with_ifdef()` - Parses includes and conditional blocks
- `sort_includes_with_ifdef()` - Sorts with 3-category rule
- `format_ifdef_block()` - Formats conditional blocks with sorted includes

## Verification

After sorting, verify:
1. All `#ifdef` blocks contain same number of headers as before
2. Corresponding header has complete path (not shortened)
3. Total include count unchanged
4. Comments preserved

Use `git diff` to compare before/after:
```bash
git diff <file.cpp> | grep "^[-+]" | grep "include"
```

Overview

This skill automatically sorts #include statements in C and C++ source files while preserving conditional compilation structure and comments. It classifies includes into corresponding header, system headers, and local headers, and inserts blank lines between groups to keep files consistent and readable. The tool supports nested #ifdef/#ifndef/#if defined blocks, #elif/#else, duplicate resolution, and validation checks to prevent lost headers.

How this skill works

The sorter parses source files and extracts plain includes and conditional blocks as units. Each unit is sorted using a three-category rule: corresponding header first (longest path if duplicates), then system headers (<>), then local headers ("") alphabetically. Conditional blocks remain intact; includes inside them are sorted and the original #ifdef/#elif/#else/#endif structure and surrounding comments are preserved. A dry-run mode shows diffs without modifying files and verification steps ensure include counts and comments are unchanged.

When to use it

  • Before committing large C/C++ refactors to make include order deterministic and review-friendly
  • When merging contributions from multiple authors to avoid noisy include-order diffs
  • To enforce project include style during CI or pre-commit checks
  • When cleaning up legacy files with inconsistent include ordering or duplicates
  • When code contains conditional compilation that must remain semantically identical

Best practices

  • Run with --dry-run first to review changes and avoid unexpected edits
  • Add the script to CI or pre-commit hooks to keep ordering consistent across the team
  • Back up or use version control so you can verify no includes were lost
  • Review preserved comments and adjacent code after sorting to confirm intent remains clear
  • Apply the tool to related translation units together to maintain expected corresponding-header placement

Example use cases

  • Sort includes in a single directory of .cpp files: quick cleanup before a release
  • Apply during a large refactor to reduce unrelated include-order changes in diffs
  • Integrate into CI to block commits that would introduce unsorted or duplicate includes
  • Normalize include order across a mixed codebase that uses many #ifdef feature flags
  • Resolve ambiguous corresponding headers by selecting longest-path duplicates automatically

FAQ

Will the tool change conditional compilation semantics?

No. The tool preserves #ifdef/#elif/#else/#endif structure and only reorders includes inside those blocks; validation checks ensure header counts remain the same.

How does it choose the corresponding header when multiple paths exist?

When duplicates exist, the longest path is chosen as the corresponding header and placed first to prefer the most specific include.