This skill should be used when the user asks to "optimize header files", "reduce header dependencies", "优化头文件", "减少头文件依赖", "analyze compilation efficiency", "分析编译效率", or mentions test_header.cpp analysis. This skill optimizes C++ header file compilation efficiency through systematic refactoring.
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
A direct command skips the review prompt. Inspect the source before running it.
This skill should be used when the user asks to "optimize header files", "reduce header dependencies", "优化头文件", "减少头文件依赖", "analyze compilation efficiency", "分析编译效率", or mentions test_header.cpp analysis. This skill optimizes C++ header file compilation efficiency through systematic refactoring.
version
1.0.0
Header File Optimization for ACE Engine
Optimize C++ header file compilation efficiency in ace_engine through systematic dependency reduction and implementation restructuring. This skill focuses on reducing compilation time and memory footprint by minimizing header dependencies and moving implementations out of headers.
When to Use This Skill
Invoke this skill when:
Optimizing specific header files for compilation efficiency
Working with test_header.cpp to analyze header dependencies
Reducing header file dependencies in ace_engine
Analyzing compilation performance of specific headers
User specifies "只分析不进行修改" (analysis only, no modifications)
Key Rules
Follow these critical constraints during optimization:
Preserve business logic - Only modify structure, not functionality
Minimize file creation - Edit current header/cpp directly, only create new files for header splitting scenarios
Limit scope - Only perform work defined in key steps, do not expand modification scope
Standalone compilation - Use compile-analysis skill for individual file compilation verification, never full build
test_header.cpp is read-only - Never modify test_header.cpp; it only serves for dependency statistics
Optimization Workflow
Step 1: Analyze Input and Mode
Determine the optimization target and mode:
If input is a header file (.h): Optimize that header directly
If input is test_header.cpp: Extract the header file from its content and optimize that header
Check if user specified "只分析不进行修改" (analysis only mode)
In analysis-only mode:
Perform all analysis steps
Generate optimization recommendations
Do NOT modify any files
Present findings and suggested changes for user approval
Step 2: Move Inline Implementations to CPP
Objective: Move all method implementations longer than 3 lines from header to cpp file.
Procedure:
Read the target header file
Identify all methods (including static methods) with implementations exceeding 3 lines
If corresponding cpp file does not exist, create it
Move method implementations to cpp file
Keep only declarations in header file
For template methods, see Step 6
What counts as 3 lines:
// Less than 3 lines - Keep in headerintGetValue()const{ return value_; }
// 3 lines or more - Move to cppvoidProcessData(){
auto result = Calculate();
Validate(result);
cache_.Store(result);
}
Exception: Simple getters/setters that are one-liners typically remain in headers for performance.
Step 3: Remove Unnecessary Header Includes
Objective: Eliminate unused header dependencies.
Procedure:
List all #include directives in the header file
For each included header, verify if it's actually used:
Search for types from that header in the file
Check if member variables, function parameters, or return types use those types
Verify base class inheritance
Remove includes that have no actual usage
Document removal reasons in analysis report
Example:
// Before#include"base/memory/ace_type.h"#include"core/components/common/layout.h"#include"core/pipeline/base/element.h"// Not used - REMOVE// After#include"base/memory/ace_type.h"#include"core/components/common/layout.h"
Step 4: Convert Includes to Forward Declarations
Objective: Replace full header includes with forward declarations wherever possible.
Procedure:
For each remaining header include, analyze what's needed from it:
Type names only (pointers, references, function parameters)
Type definitions (complete class definition needed)
Static constants or enums
Convert to forward declaration when only type name is needed:
Type is only used as template parameter for RefPtr<T> or WeakPtr<T>
Type is used as member variable with smart pointer
Type is used as function parameter/return value with smart pointer
Rule: Smart pointer templates (RefPtr, WeakPtr, std::unique_ptr, std::shared_ptr) do NOT require complete type definition in header files.
Example - Before Optimization:
// click_event.h (BEFORE)#include"core/components_ng/gestures/recognizers/click_recognizer.h"// ❌ Full includeclassClickEventActuator {
private:
RefPtr<ClickRecognizer> clickRecognizer_; // Only needs forward declarationconst RefPtr<ClickRecognizer>& GetClickRecognizer(); // Also OK with forward decl
};
Example - After Optimization:
// click_event.h (AFTER)// Removed: #include "click_recognizer.h"namespace OHOS::Ace::NG {
classClickRecognizer; // ✅ Forward declaration only
}
classClickEventActuator {
private:
RefPtr<ClickRecognizer> clickRecognizer_; // Works with forward decl
};
// click_event.cpp#include"core/components_ng/gestures/recognizers/click_recognizer.h"// Full include hereconst RefPtr<ClickRecognizer>& ClickEventActuator::GetClickRecognizer(){
if (!clickRecognizer_) {
clickRecognizer_ = MakeRefPtr<ClickRecognizer>(); // Needs full definition
}
return clickRecognizer_;
}
Key Insights:
✅ Member variables with RefPtr<T> work with forward declaration
✅ Return types const RefPtr<T>& work with forward declaration
❌ Actual instantiation MakeRefPtr<T>() requires full definition in .cpp
Verification: Compile both header and cpp to ensure no undefined type errors.
Scenario 2: Cross-Namespace Forward Declarations
When to use: When a type from one namespace is needed in another namespace's header file.
Pattern: Add forward declarations in appropriate namespace scope.
Example - gesture_event_hub.h needs ClickInfo:
// click_event.h#include"base/memory/ace_type.h"#include"core/components_ng/event/gesture_event_actuator.h"#include"ui/gestures/gesture_event.h"// Provides GestureEvent, GestureEventFunc#include"core/components_ng/event/target_component.h"// Provides GestureJudgeFunc// Cross-namespace forward declaration for gesture_event_hub.hnamespace OHOS::Ace {
classClickInfo; // Type defined in OHOS::Ace, needed by gesture_event_hub.h
}
namespace OHOS::Ace::NG {
classGestureEventHub; // Forward declaration in target namespaceclassClickRecognizer; // Forward declaration in target namespace
}
classClickEventActuator : public GestureEventActuator {
// ... implementation
};
Why this works:
When gesture_event_hub.h is included through frame_node.h → click_event.h chain
ClickInfo forward declaration is already available
Avoids circular dependencies
Reduces coupling between namespaces
Scenario 3: Replacing Indirect Dependencies with Precise Includes
Problem: Removing a heavy include (like click_recognizer.h) breaks compilation because other types were indirectly included.
Solution: Identify and directly include only the necessary type definition headers.
Example - Removing click_recognizer.h:
// BEFORE: Heavy indirect dependencies#include"core/components_ng/gestures/recognizers/click_recognizer.h"// This indirectly brought in:// - tap_gesture.h (GestureEventFunc)// - gesture_recognizer.h// - multi_fingers_recognizer.h// - And many more...// AFTER: Precise includes#include"ui/gestures/gesture_event.h"// Provides GestureEvent, GestureEventFunc#include"core/components_ng/event/target_component.h"// Provides GestureJudgeFunc// Forward declarationsnamespace OHOS::Ace::NG {
classClickRecognizer; // Only name needed for RefPtr<ClickRecognizer>
}
Analysis Process:
Search for type usages in the header (e.g., GestureEventFunc, GestureJudgeFunc)
Find their definition locations using grep/search tools
Include the header that defines the type directly
Replace heavy include with forward declaration for RefPtr/WeakPtr types
Scenario 4: Complete Decision Matrix for Forward Declarations
Usage Pattern
Can Use Forward Decl?
Requires Full Include?
T* member variable
✅ Yes
❌ No
T& parameter/return
✅ Yes
❌ No
RefPtr<T> member
✅ Yes
❌ No
RefPtr<T>& return
✅ Yes
❌ No
WeakPtr<T> member
✅ Yes
❌ No
std::unique_ptr<T>
✅ Yes
❌ No
std::shared_ptr<T>
✅ Yes
❌ No
std::vector<T>
❌ No*
✅ Yes
std::vector<T*>
✅ Yes
❌ No
Class inheritance
❌ No
✅ Yes
T member variable
❌ No
✅ Yes
T value parameter
❌ No*
✅ Yes
Template instantiation
❌ No
✅ Yes
Access static members
❌ No
✅ Yes
Access inline methods
❌ No
✅ Yes
* Exceptions exist with extern templates
Common Pitfalls and Solutions
Pitfall 1: Removing include breaks dependent headers
Symptom:
error: unknown type name 'ClickInfo' in gesture_event_hub.h
Root Cause: gesture_event_hub.h was indirectly getting ClickInfo from click_recognizer.h
Solution: Add forward declaration in appropriate namespace
namespace OHOS::Ace {
classClickInfo; // Forward declaration for gesture_event_hub.h
}
Pitfall 2: Missing type definitions after removing include
Symptom:
error: unknown type name 'GestureEventFunc'
error: unknown type name 'GestureJudgeFunc'
Root Cause: These types were indirectly included through click_recognizer.h
Solution: Directly include headers that define these types
Use compile-analysis skill to extract compilation command for the cpp file
Verify standalone compilation of the cpp file
For test_header.cpp analysis, verify it compiles with optimized header
Do NOT run full build - only standalone compilation verification
Error Handling:
If compilation fails, analyze errors
Fix missing includes or forward declarations
Re-verify until compilation succeeds
Document all fixes applied
Step 9: Measure Optimization Results
Objective: Quantify the impact of optimizations.
Metrics to Collect:
Header dependency count:
Count includes before optimization
Count includes after optimization
Calculate reduction percentage
Compilation time:
Use compile-analysis skill to measure before/after
Report time savings
Memory footprint:
Measure header file size before/after
Report reduction percentage
Lines of code:
Header file LOC reduction
New LOC added to cpp file
Result Template:
## Optimization Results
### Header: frameworks/path/to/header.h
**Before Optimization:**
- Includes: 15
- Header size: 45.2 KB
- Estimated compile impact: High
**After Optimization:**
- Includes: 6
- Header size: 12.8 KB
- Reduction: 60% includes, 72% size
**Changes Made:**
- Moved 12 method implementations to cpp
- Converted 8 includes to forward declarations
- Removed 3 unused includes
- Split constants into separate header
- Applied PIMPL pattern (if applicable)
**Compilation Status:** ✅ Verified standalone compilation
Step 10: Stage Changes with Git
Objective: Preserve optimized files in git.
Procedure:
Use git add to stage modified files:
Optimized header file
Modified or created cpp file
Any newly created split headers
Do NOT stage test_header.cpp (it's reference only)
Present staged changes to user
Generalized Optimization Strategies
This section provides generalized guidance derived from real optimization cases in ace_engine. Use these strategies to select the right optimization approach for your situation.
Strategy Selection Decision Tree
┌─────────────────────────────────────────────────────────────┐
│ What type of dependency problem? │
└─────────────────────────────────────────────────────────────┘
│
┌───────────────────┼───────────────────┐
│ │ │
Heavy include Value type Cross-namespace
within same member from include with
namespace heavy include only enum usage
│ │ │
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ RefPtr<T> │ │ unique_ptr<T> │ │ Light Include │
│ Forward Decl │ │ + Forward │ │ Replacement │
│ (Scenario 1) │ │ Declaration │ │ (Scenario 3) │
└───────────────┘ └───────────────┘ └───────────────┘
Scenario 1: RefPtr Forward Declaration (Lightest)
When to use:
Member is already RefPtr<T> or WeakPtr<T>
Only type name needed in header
No value semantics required
Pattern:
// Headernamespace OHOS::Ace::NG {
classClickRecognizer; // Forward declaration
}
classClickEventActuator {
private:
RefPtr<ClickRecognizer> clickRecognizer_; // ✅ Works with forward decl
};
// CPP#include"core/components_ng/gestures/recognizers/click_recognizer.h"const RefPtr<ClickRecognizer>& ClickEventActuator::GetClickRecognizer(){
if (!clickRecognizer_) {
clickRecognizer_ = MakeRefPtr<ClickRecognizer>(); // Full definition needed here
}
return clickRecognizer_;
}
⚠️ CRITICAL: RefPtr Members CAN Use Forward Declarations
Common misconception: "RefPtr members require complete type definition"
✅ Correct understanding: RefPtr members work perfectly with forward declarations, provided that:
All inline methods that use the RefPtr member are moved to .cpp
Any method that calls member_->Method() must be in .cpp
Any method that calls MakeRefPtr<T>() must be in .cpp
Any method with RefPtr<T> parameter or return type should be in .cpp
Only declarations remain in header
RefPtr<T> member_; ✅ Works with forward declaration
RefPtr<T> GetMember(); ✅ Declaration only
void SetMember(const RefPtr<T>& member); ✅ Declaration only
No inline instantiation in header
❌ MakeRefPtr<T>() calls in header
❌ member_->Method() calls in header
✅ Both must be in .cpp implementation
Example from gesture_recognizer.h optimization:
// gesture_recognizer.h - BEFORE (inline implementations)classNGGestureRecognizer {
boolIsSystemGesture()const{ // ❌ Inline - needs full GestureInfo definitionif (!gestureInfo_) returnfalse;
return gestureInfo_->IsSystemGesture();
}
RefPtr<GestureInfo> GetGestureInfo(){ // ❌ Inline - returns RefPtr<GestureInfo>return gestureInfo_;
}
private:
RefPtr<GestureInfo> gestureInfo_; // ❌ Requires full definition due to inline methods
};
// gesture_recognizer.h - AFTER (forward declaration + declarations)namespace OHOS::Ace::NG {
classGestureInfo; // ✅ Forward declaration only
}
classNGGestureRecognizer {
boolIsSystemGesture()const; // ✅ Declaration onlyRefPtr<GestureInfo> GetGestureInfo(); // ✅ Declaration onlyprivate:
RefPtr<GestureInfo> gestureInfo_; // ✅ Works with forward declaration!
};
// gesture_recognizer.cpp - Full implementations#include"core/components_ng/event/gesture_info.h"// ✅ Full include hereboolNGGestureRecognizer::IsSystemGesture()const{
if (!gestureInfo_) returnfalse;
return gestureInfo_->IsSystemGesture(); // ✅ Full definition available
}
RefPtr<GestureInfo> NGGestureRecognizer::GetGestureInfo(){
return gestureInfo_; // ✅ Can return RefPtr with full definition
}
Key principle: RefPtr members do NOT require complete type definition in the header. The requirement comes from inline methods that use the member, not from the member itself.
Benefits:
✅ No destructor separation needed (RefPtr manages lifecycle)
✅ Minimal code changes
✅ Zero runtime overhead
✅ Existing pattern in ace_engine
Real case: case-click_event-forward-declaration.md
Complexity: Easy
Scenario 2: Value Type → unique_ptr Conversion
When to use:
Value type member from heavy include
Member only used in implementation (.cpp)
Want to remove heavy include dependency
Can accept small runtime overhead (heap allocation)
Cause: Changed member to unique_ptr but still returning by value
Solution: Change return type to const T&
Pitfall 3: Missing Dereference
Symptom: Compile error when passing smart pointer to function
Cause: Forgetting to dereference unique_ptr when value type expected
Solution: Use conditional dereference pattern:
function(ptr ? *ptr : Type());
Pitfall 4: Const Static Initialization Failure
Symptom: Static initialization fails for complex types
Cause: Using static const T with complex constructor
Solution: Use static T (non-const) as fallback
Additional Resources
Reference Files
For detailed techniques and examples:
references/patterns.md - Common refactoring patterns for header optimization
references/pimp-guide.md - PIMPL pattern detailed guide with ace_engine examples
references/forward-declaration.md - Forward declaration best practices
references/case-split-enums.md - Real case study: Splitting enums from drag_event.h to drag_constants.h (90%+ dependency reduction)
references/case-click_event-forward-declaration.md - Real case study: RefPtr forward declaration optimization for click_event.h (35% size reduction, smart pointer optimization patterns)
references/case-drag-drop-forward-declaration.md - ✨ NEW: Real case study: unique_ptr conversion for value type members in drag_drop_related_configuration.h
references/case-drag-event-include-reduction.md - ✨ NEW: Real case study: Light include replacement strategy for cross-namespace dependencies in drag_event.h
Examples
Working examples in examples/:
before-after/ - Side-by-side comparisons of optimizations
pimpl-example/ - Complete PIMPL implementation example
split-header/ - Header splitting example
Scripts
Utility scripts in scripts/:
analyze-includes.sh - Analyze header include dependencies
extract-includes.py - Extract include statistics from headers