Any tools to find duplicate #include?

It sounds strange, but maybe there is one ... I searched for it but I couldn't find anything.
simple example:
I have one class1.h file:

#include "a.h"
#include "b.h"


another class2.h file:

#include "a.h"
#include "c.h"


and main.cpp:

#include "class2.h" //as we see here, we getting "a.h" double included by class1.h and class2.h


I want to get rid of such deceptions in my project.

of course, as an example it is not so difficult, but I have a huge number of files that are largely related to each other and it is difficult to trace all the deceptions.

any suggestions before i am going to write this tool myself? :)


source to share

4 answers

As I see it, if the code in the file depends on other stuff to be declared, it should include the file containing those declarations. Otherwise, the material becomes brittle and includes all the time and in a certain order, and the whole thing becomes ugly. So for me "duplicate includes" is good; each piece of code can take care of its dependencies with fewer problems.

As for how to keep things from breaking in the duplicate, there is ... there is an idiom called "include guards." They look a little something like this ...


#ifndef FILE1_H
#define FILE1_H

(the meat of file1.h goes in here)



The first time this file is included, FILE1_H

it is not yet defined (or should not be if you choose better names for your files than this), so the code is included (and FILE1_H

subsequently defined). The next time it is enabled is FILE1_H

now defined, so the code is skipped.

(By the way, any macro name will work for this as long as it is unique for each file. But this limitation is the biggest reason the macro name is almost always based on the file name.)

Most compilers work #pragma once

. But this is not a standard; if you care about being able to use whatever compiler you want then don't use it (or use it in addition to the include guard).



You must use Include Guard so that you do not include the same multiplex times at the same headers.

Once you have Include guards, you don't need to include header files multiple times. It is good practice that every source or header file should include the header files required for independent compilation, that is: Do not rely on inclusion through other included files.



Besides what @Als said, start using forward declarations.



I have used #pragma once

extensively with my C ++ projects, but as I heard somewhere, it may not work for all compilers, but if you are using Microsoft Visual Studio this works (I used it in VC ++ 6.0, 2005 and 2010 biennium)



All Articles