Include what you use windows

Include What You Use

IWYU CI

For more in-depth documentation, see docs.

Instructions for users

«Include what you use» means this: for every symbol (type, function, variable, or macro) that you use in foo.cc (or foo.cpp), either foo.cc or foo.h should include a .h file that exports the declaration of that symbol. (Similarly, for foo_test.cc, either foo_test.cc or foo.h should do the including.) Obviously symbols defined in foo.cc itself are excluded from this requirement.

This puts us in a state where every file includes the headers it needs to declare the symbols that it uses. When every file includes what it uses, then it is possible to edit any file and remove unused headers, without fear of accidentally breaking the upwards dependencies of that file. It also becomes easy to automatically track and update dependencies in the source code.

CAVEAT

This is alpha quality software — at best (as of July 2018). It was originally written to work specifically in the Google source tree, and may make assumptions, or have gaps, that are immediately and embarrassingly evident in other types of code.

While we work to get IWYU quality up, we will be stinting new features, and will prioritize reported bugs along with the many existing, known bugs. The best chance of getting a problem fixed is to submit a patch that fixes it (along with a test case that verifies the fix)!

Clang compatibility

Include-what-you-use makes heavy use of Clang internals, and will occasionally break when Clang is updated. We build IWYU regularly against Clang mainline to detect and fix such compatibility breaks as soon as possible.

NOTE: the IWYU master branch follows Clang main branch.

We also have convenience tags and branches for released versions of Clang (called clang_<version>, e.g. clang_5.0). To build against a Clang release, check out the corresponding branch in IWYU before configuring the build. You can use this mapping table to combine Clang and IWYU versions correctly:

Clang IWYU version IWYU branch
3.6 0.4 clang_3.6
3.7 0.5 clang_3.7
3.8 0.6 clang_3.8
3.9 0.7 clang_3.9
4.0 0.8 clang_4.0-r2
5.0 0.9 clang_5.0
6 0.10 clang_6.0
7 0.11 clang_7.0
8 0.12 clang_8.0
9 0.13 clang_9.0
10 0.14 clang_10
11 0.15 clang_11
12 0.16 clang_12
13 0.17 clang_13
14 0.18 clang_14
15 0.19 clang_15
16 0.20 clang_16
main master

NOTE: If you use the Debian/Ubuntu packaging available from https://apt.llvm.org, you’ll need the following packages installed:

  • llvm-<version>-dev
  • libclang-<version>-dev
  • clang-<version>

Packaging for other platforms will likely be subtly different.

How to build standalone

This build mode assumes you already have compiled LLVM and Clang libraries on your system, either via packages for your platform or built from source. To set up an environment for building IWYU:

  • Create a directory for IWYU development, e.g. iwyu

  • Clone the IWYU Git repo:

    iwyu$ git clone https://github.com/include-what-you-use/include-what-you-use.git
    
  • Presumably, you’ll be building IWYU with a released version of LLVM and Clang, so check out the corresponding branch. For example, if you have Clang 6.0 installed, use the clang_6.0 branch. IWYU master tracks LLVM & Clang main:

    iwyu$ cd include-what-you-use
    iwyu/include-what-you-use$ git checkout clang_6.0
    
  • Create a build root and use CMake to generate a build system linked with LLVM/Clang prebuilts:

    # This example uses the Makefile generator, but anything should work.
    iwyu/include-what-you-use$ cd ..
    iwyu$ mkdir build && cd build
    
    # For IWYU 0.10/Clang 6 and earlier
    iwyu/build$ cmake -G "Unix Makefiles" -DIWYU_LLVM_ROOT_PATH=/usr/lib/llvm-6.0 ../include-what-you-use
    
    # For IWYU 0.11/Clang 7 and later
    iwyu/build$ cmake -G "Unix Makefiles" -DCMAKE_PREFIX_PATH=/usr/lib/llvm-7 ../include-what-you-use
    

    (substitute the llvm-6.0 or llvm-7 suffixes with the actual version compatible with your IWYU branch)

    or, if you have a local LLVM and Clang build tree, you can specify that as CMAKE_PREFIX_PATH for IWYU 0.11 and later:

    iwyu/build$ cmake -G "Unix Makefiles" -DCMAKE_PREFIX_PATH=~/llvm-project/build ../include-what-you-use
    
  • Once CMake has generated a build system, you can invoke it directly from build, e.g.

How to build as part of LLVM

Instructions for building LLVM and Clang are available at https://clang.llvm.org/get_started.html.

To include IWYU in the LLVM build, use the LLVM_EXTERNAL_PROJECTS and LLVM_EXTERNAL_*_SOURCE_DIR CMake variables when configuring LLVM:

  llvm-project/build$ cmake -G "Unix Makefiles" -DLLVM_ENABLE_PROJECTS=clang -DLLVM_EXTERNAL_PROJECTS=iwyu -DLLVM_EXTERNAL_IWYU_SOURCE_DIR=/path/to/iwyu /path/to/llvm-project/llvm
  llvm-project/build$ make

This builds all of LLVM, Clang and IWYU in a single tree.

How to install

If you’re building IWYU out-of-tree or installing pre-built binaries, you need to make sure it can find Clang built-in headers (stdarg.h and friends.)

Clang’s default policy is to look in path/to/clang-executable/../lib/clang/<clang ver>/include. So if Clang 3.5.0 is installed in /usr/bin, it will search for built-ins in /usr/lib/clang/3.5.0/include.

Clang tools have the same policy by default, so in order for IWYU to analyze any non-trivial code, it needs to find Clang’s built-ins in path/to/iwyu/../lib/clang/3.5.0/include where 3.5.0 is a stand-in for the version of Clang your IWYU was built against.

Note that some distributions/packages may have different defaults, you can use clang -print-resource-dir to find the base path of the built-in headers on your system.

So for IWYU to function correctly, you need to copy the Clang include directory to the expected location before running (similarly, use include-what-you-use -print-resource-dir to learn exactly where IWYU wants the headers).

This weirdness is tracked in issue 100, hopefully we can make this more transparent over time.

How to run

The original design was built for Make, but a number of alternative run modes have come up over the years.

Running on single source file

The simplest way to use IWYU is to run it against a single source file:

  include-what-you-use $CXXFLAGS myfile.cc

where $CXXFLAGS are the flags you would normally pass to the compiler.

Plugging into existing build system

Typically there is already a build system containing the relevant compiler flags for all source files. Replace your compiler with include-what-you-use to generate a large batch of IWYU advice. Depending on your build system/build tools, this can take many forms, but for a simple GNU Make system it might look like this:

  make -k CXX=include-what-you-use CXXFLAGS="-Xiwyu --error_always"

(The additional -Xiwyu --error_always switch makes include-what-you-use always exit with an error code, so the build system knows it didn’t build a .o file. Hence the need for -k.)

In this mode include-what-you-use only analyzes the .cc (or .cpp) files known to your build system, along with their corresponding .h files. If your project has a .h file with no corresponding .cc file, IWYU will ignore it unless you use the --check_also switch to add it for analysis together with a .cc file. It is possible to run IWYU against individual header files, provided the compiler flags are carefully constructed to match all includers.

Using with CMake

CMake has grown native support for IWYU as of version 3.3. See their documentation for CMake-side details.

The CMAKE_CXX_INCLUDE_WHAT_YOU_USE option enables a mode where CMake first compiles a source file, and then runs IWYU on it.

Use it like this:

  mkdir build && cd build
  CC="clang" CXX="clang++" cmake -DCMAKE_CXX_INCLUDE_WHAT_YOU_USE=include-what-you-use ...

or, on Windows systems:

  mkdir build && cd build
  cmake -DCMAKE_CXX_COMPILER="%VCINSTALLDIR%/bin/cl.exe" -DCMAKE_CXX_INCLUDE_WHAT_YOU_USE=include-what-you-use -G Ninja ...

These examples assume that include-what-you-use is in the PATH. If it isn’t, consider changing the value to an absolute path. Arguments to IWYU can be added using CMake’s semicolon-separated list syntax, e.g.:

  ... cmake -DCMAKE_CXX_INCLUDE_WHAT_YOU_USE="include-what-you-use;-w;-Xiwyu;--verbose=7" ...

The option appears to be separately supported for both C and C++, so use CMAKE_C_INCLUDE_WHAT_YOU_USE for C code.

Note that with Microsoft’s Visual C++ compiler, IWYU needs the --driver-mode=cl argument to understand the MSVC options from CMake.

Using with a compilation database

The iwyu_tool.py script pre-dates the native CMake support, and works off the compilation database format. For example, CMake generates such a database named compile_commands.json with the CMAKE_EXPORT_COMPILE_COMMANDS option enabled.

The script’s command-line syntax is designed to mimic Clang’s LibTooling, but they are otherwise unrelated. It can be used like this:

  mkdir build && cd build
  CC="clang" CXX="clang++" cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ...
  iwyu_tool.py -p .

or, on Windows systems:

  mkdir build && cd build
  cmake -DCMAKE_CXX_COMPILER="%VCINSTALLDIR%/bin/cl.exe" -DCMAKE_C_COMPILER="%VCINSTALLDIR%/VC/bin/cl.exe" -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -G Ninja ...
  python3 iwyu_tool.py -p .

Unless a source filename is provided, all files in the project will be analyzed.

See iwyu_tool.py --help for more options.

Applying fixes

We also include a tool that automatically fixes up your source files based on the IWYU recommendations. This is also alpha-quality software! Here’s how to use it (requires python3):

  make -k CXX=include-what-you-use CXXFLAGS="-Xiwyu --error_always" 2> /tmp/iwyu.out
  python3 fix_includes.py < /tmp/iwyu.out

If you don’t like the way fix_includes.py munges your #include lines, you can control its behavior via flags. fix_includes.py --help will give a full list, but these are some common ones:

  • -b: Put blank lines between system and Google includes
  • --nocomments: Don’t add the ‘why’ comments next to includes

How to correct IWYU mistakes

  • If fix_includes.py has removed an #include you actually need, add it back in with the comment ‘// IWYU pragma: keep‘ at the end of the #include line. Note that the comment is case-sensitive.
  • If fix_includes.py has added an #include you don’t need, just take it out. We hope to come up with a more permanent way of fixing later.
  • If fix_includes.py has wrongly added or removed a forward-declare, just fix it up manually.
  • If fix_includes.py has suggested a private header file (such as <bits/stl_vector.h>) instead of the proper public header file (<vector>), you can fix this by inserting a specially crafted comment near top of the private file (assuming you can write to it): ‘// IWYU pragma: private, include "the/public/file.h"‘.

Current IWYU pragmas are described in IWYUPragmas.

Platform tweaks

libc++

When analyzing C++ code on macOS, IWYU uses probing (implicitly via Clang) to find a libc++ standard library installation.

If there is no installation of libc++ discoverable to Clang’s probing, or an alternative libc++ is desired, users can specify relevant paths directly on command-line, e.g.:

# for Homebrew version of llvm-14
include-what-you-use \
    -nostdinc++ \
    -isystem /opt/homebrew/opt/llvm\@14/include/c++/v1 \
    sourcefile.cc

# for Apple Command Line Tools version of libc++
include-what-you-use \
    -nostdinc++ \
    -isystem /Library/Developer/CommandLineTools/usr/include/c++/v1 \
    sourcefile.cc

The mechanics of this technique are described in more detail for Clang here: https://libcxx.llvm.org//UsingLibcxx.html#using-a-custom-built-libc.

To find the SDK install root, use:

xcrun --sdk macosx --show-sdk-path

Append /usr/include/c++/v1 to that path to get the libc++ root.

The libc++ library helpfully ships with a set of IWYU mappings, see their documentation for details: https://libcxx.llvm.org/UsingLibcxx.html#include-what-you-use-iwyu.

«Include what you use» means this: for every symbol (type, function variable, or macro) that you use in foo.cc, either foo.cc or foo.h should #include a .h file that exports the declaration of that symbol. The include-what-you-use tool is a program that can be built with the clang libraries in order to analyze #includes of source files to find include-what-you-use violations, and suggest fixes for them.

The main goal of include-what-you-use is to remove superfluous #includes. It does this both by figuring out what #includes are not actually needed for this file (for both .cc and .h files), and replacing #includes with forward-declares when possible.

Features

Optimize the include files for the current C/C++ file:

Include What You Use

Requirements

You will need to install include-what-you-use. For example on mac:

brew install include-what-you-use

You must have a Python interpreter on the path that will be used. Both python 2/3 should work. This extension includes
code from include-what-you-use, which uses the LLVM license. See the LICENSE file for details.

Extension Settings

This extension contributes the following settings:

  • iwyu.exe: Path to the include what you use executable.
  • compile_commands Path to compile_commands.json file.
  • iwyu.mapping_file: Mapping file to use. See IWYU Mappings for details.
  • iwyu.transitive_includes_only: Do not suggest that a file add foo.h unless foo.h is already visible in the file’s transitive includes.
  • iwyu.max_line_length: Maximum line length for includes.Note that this only affects comments and alignment thereof, the maximum line length can still be exceeded with long file names
  • iwyu.no_default_mappings: Do not add iwyu’s default mappings.
  • iwyu.no_fwd_decls: Do not use forward declarations.
  • iwyu.keep: A glob that tells iwyu to always keep these includes. Can be provided multiple times.
  • iwyu.additional_params: Additional parameters you wish to pass to iwyu. Must be prefixed with a -Xiwyu flag
  • iwyu.comments: Put comments after the #include lines.»
  • iwyu.safe: Do not remove unused #includes/fwd-declares from header files; just add new ones.
  • iwyu.reorder: Re-order lines relative to other similar lines (e.g. headers relative to other headers).
  • iwyu.ignore_re: Skip editing any file whose name matches this regular expression.
  • iwyu.only_re: Skip editing any file whose name does NOT match this regular expression.

How to Correct IWYU Mistakes

Taken from IWYU:

  • If the extension has removed an #include you actually need, add it back in with the comment ‘// IWYU pragma: keep‘ at the end of the #include line. Note that the comment is case-sensitive.
  • If the extension has added an #include you don’t need, just take it out.
  • If the extension has wrongly added or removed a forward-declare, just fix it up manually.
  • If the extension is inserting private headers (such as <bits/stl_vector.h>) v.s. public ones (<vector>), you can consider creating a mapping file or you can fix this by inserting a specially crafted comment near top of the private file (assuming you can write to it): ‘// IWYU pragma: private, include "the/public/file.h"‘.
    .

Known Issues

  • You will need a python interpreter on the path.

Release Notes

1.0.3

  • Add support for passing parameters to the python post processor, this enables
    aggressive rewrites with removal of unused #includes. Note: This is not perfect.

1.0.2

  • Fixed typo in mapping_file parameter.

1.0.1

  • Add some additional properties.
  • Removed mapping_files property and replaced it with single mapping file that can be set using iwyu.mapping_file
  • Removed why option, as it can break automated fixing.
  • Parse compile_commands.json when a change has been detected.
  • Mention that a python interpeter is needed.
  • Lower minimum version of vscode to 1.38.0

1.0.0

Initial release of include what you use.

Published January 1, 2021

I’ve used the clang based include-what-you-use tool on a fairly large chunk of code — a couple of hundreds of files, containing dozens of includes each.

That was an interesting experiment.

Here are my takeaways on this powerful tool, what it can bring to your code, and a few things I wish I had known when I started using it.

include-what-you-…what?

include-what-you-use is a clang-based library that reworks the #includes sections of a C++ file, be there a header or a .cpp file.

The tool has two goals: make sure that each file:

  • #includes all the headers that it uses, meaning all headers that define or declare a symbol that is used by the including file.
  • and doesn’t #include any unnecessary header, meaning any header that defines or declares symbols that are not used by including file.

The first goal correspond to the name of the tool, “include what you use”, and the second one could be called “use what you include”.

Said differently, include-what-you-use makes sure that your headers and .cpp files include everything they need and nothing more.

The benefits of having clean header inclusions

There are multiple benefits in having such clean header inclusions.

Design benefit

One of them is that it gives you better vision of dependencies between files. After executing the cleaning with the tool, nearly every remaining (or added) #include represents a dependency (I say nearly because some #includes don’t count as dependencies: for example a class implementation file that #includes its own header file).

Indeed, if a file needs a #include, it means that it uses the code in that #included file. That’s a dependency.

Before cleaning the header inclusions, some #includes may not be necessary. They can be remains of old developments, whose code has be deleted or refactored away to other files modules. Indeed, when changing code, it’s easy to forget to update the #includes.

Those remaining useless #includes create a shallow dependency: a dependency of compilation, because the compiler (or rather, the preprocessor) executes the inclusion, but not a design dependency, because no code really depends on that inclusion.

On the other hand, there can be symbols that the code of a file uses and that are not in the #includes of that file. This happens if those symbol are defined in files that are indirectly included. In this case, the #include section doesn’t give the full picture of the dependencies of the file.

After the header cleanup, you can see the exact dependencies of a given file.

Seeing dependencies is valuable because it is a good start for refactoring: if you see a dependency that doesn’t make sense, then you can work towards removing it. This helps improve the design and architecture of the code, which makes it easier to understand.

Other benefits

Another interesting benefit in cleaning header inclusions is that it can reduce them, and therefore reduce compilation time. Indeed, if you change a header that is #included by many files, re-building your project takes time as it involves to recompile a large amount of files.

Removing useless inclusions can therefore reduce compilation time, without changing the outcome of the compilation. The compiler just stops making unnecessary work.

Another benefit of cleaning up is that clean headers are self-inclusive. This means that if you were to compile them on their own, they would compile without errors, and in particular without missing files.

In fact, self-inclusive headers is more a necessity that a benefit. Without self-inclusive header, you can’t #include headers in any order, because they depend on the #includes of each other.

Without self-inclusive errors, you can get weird problems, such as changing a header and having compilation errors popping up in an unrelated file that you then need to fix because it wasn’t self-inclusive and relied on the header you’re changing.

The errors generated by the cleaning

Although a powerful tool, include-what-you-use isn’t a perfect one, as some files no longer compile after cleaning.

I haven’t see a recurring pattern but here are some of the errors I saw:

  • two namespaces having the same symbol got mixed up once,
  • a declaration was #included instead of a definition,
  • a given file was not #included where it was needed.

It may just be me incorrectly configuring the tool, or it may be bugs in the tool. It doesn’t matter that much, as those were very sparse errors in comparison with the volume of code that the tool treated correctly.

But what is useful to know is that sparse errors can generate a very, very large volume of error messages. Indeed, if those errors happen to be located in central header files, then the errors get generated in many compilation units.

As a result, the amount of errors messages can be daunting at first sight.

Treating errors

The best way I’ve found to treat those errors is to be very methodic.

First, group the errors by file. Maybe your IDE will do it for you, or if you get a raw output from your compiler you can put them into a Pivot Table in Excel in order to extract the file names and count duplicates.

Removing duplicate errors ensures that you won’t see the same error more than once. In my case, one single wrong include was responsible of more than half of the error messages! Fixing it took a few seconds, and it reduced the number of errors left to treat by two. This is energizing.

Taking care of the errors file by file also allows to accelerate the fixes, because you won’t have to jump from one file to another all the time.

All in all, it took me little time to go over the remaining changes to make after the tool ran, and all this experiment had a dramatic effect on the header inclusions of the files.

Make your code include what it uses

In conclusion, I recommend that you try include-what-you-use on your code, in order to clarify its dependencies, improve its compilation time and ensure that headers are self-inclusive.

When you do, please leave a comment here to let me know how that went, and if you have additional advice about how to use the tool efficiently.

And if you already tried it, please let us know about your experience now!

You will also like

  • Technical Debt Is like a Tetris Game
  • TODO_BEFORE(): A Cleaner Codebase for 2019
  • 10 Code Smells a Static Analyser Can Locate in a Codebase
  • Mikado Refactoring with C++ Feature Macros
  • The Shapes of Code

Don’t want to miss out ? Follow:   
Share this post!

In a nutshell, include what you use (iwyu), introduced by Google, ensures source files include all headers used in the C++ code. This c++ include what you use methodology essentially maximizes the probability that code continues to compile even with reasonable changes made to the various interfaces. 

Previously I wrote to you about the “include what you use” tool.  It will automatically suggest forward declarations to speed up compile times, as well as missing includes to detect (accidental) reliance on indirect includes, which may not be portable.

However, if you run it you might notice a couple of false positives.

Problem: Guaranteed Indirect Includes

Problem

The first thing you notice is that following the “include what you use” philosophy can get a little bit annoying at times.

It is a common practice to have an “convenience header” that includes many other headers.

A lot of the Boost C++ libraries follow this practice. For example, here we include boost/mp11.hpp to get access to all meta programming facilities provided by Boost.Mp11:


#include <boost/mp11.hpp>

using my_types = boost::mp11::mp_list<int, char, float>;

But IWYU doesn’t know about that and instead suggests we include boost/mp11/detail/mp_list.hpp to get mp_list which is obviously wrong.

If you are writing the library, you can fix it with a special comment // IWYU pragma: export:

// somewhere in a Boost.Mp11 header file
#include <boost/mp11/detail/mp_list.hpp> // IWYU pragma: export

This will tell IWYU that the contents of this include are guaranteed to be available when including the header file.

Tip: When writing “convenience headers” for libraries intended to be used with iwyu , use // IWYU pragma: export (or a more general begin_exports/end_exports) to mark guaranteed indirect includes.

If you are not writing the library, there is a // iwyu pragma: keep to tell iwyu that you want to keep a given include, but there is no pragma to say that this is actually the correct include.

A list of all pragmas can be found here: https://github.com/include-what-you-use/include-what-you-use/blob/master/docs/IWYUPragmas.md

Non-intrusive Pragmas: Mapping Files

Solution

But there is a non-intrusive solution to the problem: a mapping file. In it you can define which headers should be suggested for which symbols.

In our example, we want to say that boost::mp11::mp_list is provided by boost/mp11.hpp. So we create an mp11.imp file with the following contents:


[
{ symbol: ["boost::mp11::mp_list", "private", "<boost/mp11.hpp>", "public"] }
]

It has a JSON like syntax containing an array of directives. Here we use the symbol directives specifying that the given symbol (boost::mp11::mp_list) with the given visibility (it must always be private for some reason) is provided by the given header (boost/mp11.hpp) with the given header visibility (usually public).

Then we simply pass that file to iwyu with -Xiwyu –mapping_file=mp11.imp, and IWYU will no longer complain.

Tip: Use a symbol mapping to override the headers iwyu will suggest you include for it.

This can be done for all symbols but is tedious.

Luckily there is a better way: We can use the include directive to remap a header file to a different header file, or an entire directory to a header file:


[
{ include: ["@<boost/mp11/.*>", "public", "<boost/mp11.hpp>", "public"] }
]

The @ introduces a wild card, so here we are mapping all headers found in the given directory — which are considered public — to boost/mp11.hpp — which is also public.

Then iwyu will not suggest any of the headers of boost/mp11/* but boost/mp11.hpp instead. Since we already include it, it will not complain at all.

Tip: Use an include mapping to map one header file or multiple header files to a different header file.

The final directive is ref, this allows merging multiple .imp files together.

See the full documentation of mapping files here: https://github.com/include-what-you-use/include-what-you-use/blob/master/docs/IWYUMappings.md

Conclusion

Personally, I don’t bother with mapping files. I don’t need to because I don’t run iwyu in an automated fashion. I just run it manually and review the suggested changes.

Doing that is definitely worth the trouble. I was able to improve compilation times noticeable by cleaning up some unnecessary include directives.

But hopefully, modules will make it obsolete in the near future.

Take c++ include what you use (iwyu) to the Next Level

Companies from the Gaming, Automotive, Finance, and other leading sectors today are facing a growing demand for increased computing power during peak times, along with escalating pressure to improve their time to market. These challenges cannot be accomplished only by using iwyu.

Incredibuild’s cutting-edge solution accelerates a wide range of time-consuming tasks, such as builds, tests and more, by distributing them across the user’s local network or VM’s and running them simultaneously. This ensures speed, accuracy, and visibility to organizations of all sizes in one comprehensive package.

Jonathan Müller (Guest)

Jonathan, a C++ expert, works on various C++ projects, writes libraries, speaks at conferences and blogs about library development at foonathan.net

July 11th, 2023

#include cleanup 

Visual Studio now offers #include cleanup, a feature that improves the quality of your code by generating suggestions to remove unused headers and add direct headers. Our suggested workflow is to first go through the direct include suggestions to add direct headers where indirect headers are used, followed by removing the unused includes.

Remove unused #include statements 

This feature provides suggestions to remove unused headers from your files, enhancing code cleanliness. When an unused include is detected, it is visually dimmed by default. By hovering over the dimmed include, a quick action (indicated by three dots in the default view) prompt will appear, notifying you about the unused include in the file. You can click on the light bulb to remove the unused include or all unused includes. This makes it easier to clean up your code and ensures that you keep only the necessary includes to keep your code well-organized.

Gif showing remove unused includes.

Gif showing remove unused includes.

Add transitively used #include statements 

In Visual Studio, there is an existing feature that alerts users when an include is used but not added to the file. This is indicated by a squiggle and suggests adding the required include. Currently, we have added a new feature that provides suggestions for adding direct includes when your file has indirect dependencies. Including indirect dependencies can result in longer compilation times. However, with the help of direct include suggestions, you can optimize compilation time by including only the essential direct dependencies.

In instances where the direct include for certain content is missing, a quick action (indicated by three dots in the default view) will appear. Hovering over it will inform you that content from that transitive include is being used. Then, you have the option to either add all transitively used includes. By choosing to include all transitively used includes, all the direct headers will be automatically added wherever indirect headers are used in the file. After including the direct dependencies, it is crucial to remove any unused includes, retaining only those that are necessary.

Gif showing add direct include suggestion.

Gif showing add direct include suggestion.

To quickly perform code cleanup, you can configure code cleanup by adding “Add transitively used and remove unused #include statements (C++)”. Once this setup is complete, you’ll have the convenience of adding all transitively used includes and removing all unused includes with just a single click on the broom icon. This streamlines the process and ensures that your code remains clean.

Gif displaying Configure Code Cleanup

Gif displaying Configure Code Cleanup.

By default, #include cleanup is disabled, but you can enable it by navigating to Tools > Options > Text Editor > C/C++ > IntelliSense and selecting “Enable #include cleanup.” Once enabled, you have the flexibility to adjust the settings and configure different levels to meet your specific needs and preferences.

Image displaying Code cleanup setting.

Image displaying code cleanup setting.

Customization Options

You have the flexibility to customize how the #include cleanup generates suggestions, allowing it to seamlessly adapt and integrate with intricate and extensive codebases. By making these changes or adjustments, you can ensure that the process better aligns with the specific needs and complexities of your project, resulting in a more efficient and effective code cleanup. In the EditorConfig (EditorConfig settings), you can add a single header, and if you want to include multiple headers, you should separate them using commas.

 

To exclude specific includes from #include cleanup suggestions, you can utilize EditorConfig. This allows you to categorize and define which files should not be considered for suggestions, providing greater control over the suggestions generated by #include cleanup.
Examples of excluding single and multiple files (exclude vcruntime.h and vcruntime_string.h from cleanup suggestions):

cpp_include_cleanup_excluded_files = vcruntime.h
cpp_include_cleanup_excluded_files = vcruntime.h,vcruntime_string.h
Required Files

In cases where headers require other headers, and you don’t want suggestions generated, you can specify the dependencies in the EditorConfig. This ensures that required files won’t be marked as unused.
Examples of single and multiple required files (atlwin.h requires altbase.h and atlcom.h requires altbase.h):

cpp_include_cleanup_required_files = atlwin.h:altbase.h
cpp_include_cleanup_required_files = atlwin.h:altbase.h,atlcom.h:altbase.h
Files Replacement

This feature also supports the remapping of facade headers. If a file is intended to represent a different file, you can redirect the usage of the first file to the usage of the second file in EditorConfig.
Examples of single and multiple replaced files (replace stdio.h by cstdio, and replace stdint.h by cstdint):

cpp_include_cleanup_replacement_files = stdio.h:cstdio
cpp_include_cleanup_replacement_files = stdio.h:cstdio,stdint.h:cstdint
Alternate Files 

In certain situations, you may have alternative options for including a file, such as facade files. When the usage of one file can be considered as an alternative to the usage of another file, you can specify this relationship in EditorConfig. By doing so, you can prevent #include cleanup from generating suggestions for alternate matches.
Examples of single and multiple alternate files (windows.h is an alternate for minwindef.h and windows.h is an alternate for winerror.h):

cpp_include_cleanup_alternate_files = windows.h:minwindef.h
cpp_include_cleanup_alternate_files = windows.h:minwindef.h,windows.h:winerror.h

Send us your feedback! 

Explore #Include Cleanup by downloading the latest version of Visual Studio Preview. We genuinely value your feedback as it plays a crucial role in shaping our development process. Please share your thoughts in the comments below, on Developer Community, or reach out to us on Twitter (@VisualC) or via email at visualcpp@microsoft.com. Your input is highly appreciated! 

  • Include masm32 include windows inc
  • Install java 64 bit windows 10
  • Inshot скачать на компьютер для windows скачать бесплатно
  • Install iis on windows 10
  • Insert your windows installation or recovery media