llvm / llvm/llvm-project

[clang-tidy] checker to use forward declarations for optimizing headers inclusions

Open
#171,601 4 comments 0 reactions 0 assignees View on GitHub
check-request clang-tidy
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

**Motivation**

C++ developers often make suboptimal use of #include directives in header files, which leads to:

- Slower compilation times due to redundant inclusions;
- Potential circular dependencies between header files;
- Increased size of precompiled headers.

In C++, forward declarations of classes can be used instead of full header inclusions when:

1. The type is used only through a pointer or reference;
2. Class methods are not called or member access is not required;
3. Knowledge of the class size is not required (e.g., for `sizeof` or some containers).

**The goal of new checker**

Detect cases where a full header inclusion can be replaced with a forward declaration without violating the semantics of the program.

**Before**

```
// bar.hpp
#pragma once
#include "foo.hpp" // Extra inclusion slows down compilation
void process(const foo&); // Only forward declaration would be enough
```

**After**

```
// bar.hpp
#pragma once
class foo; // forward declaration instead of full inclusion
void process(const foo&);
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.