jiafu
jiafu

Reputation: 6556

how to check if one header include another header in c++?

how to check if one header include another header in c++?

for example, When I want to know if the include , but the include two many headers and header include other headers.So I have to check the source code one by one, So is there any quick method to find if one include another?

Upvotes: 1

Views: 364

Answers (3)

justin
justin

Reputation: 104728

in some cases, the header guard mentioned in other answers will not suffice (e.g. your file is used on multiple systems or is built against separate versions or libraries and the hguard is inconsistent). In those cases, you can:

  • look for another identifier which is #defined in that header
  • or simply replace your inclusion of that header with your own little wrapper header which has a #define which does not vary by platform/architecture, then replace your #includes with the wrapper header. To illustrate:

    #ifndef MON_HGUARD_CXX_CSTDIO
    #define MON_HGUARD_CXX_CSTDIO
    
    // now replace the following #include with inclusion of this header
    #include <cstdio>
    
    #endif // MON_HGUARD_CXX_CSTDIO
    

Upvotes: 0

athwaites
athwaites

Reputation: 433

You should use an include guard. This will ensure the compiler does not include the header contents more than once.

An example header file, MyClass.h, using a standard include guard:

// MyClass.h

#ifndef MYCLASS_H
#define MYCLASS_H

// Your header contents goes here

#endif

This will ensure that the compiler only includes the header contents once.

Alternatively, you can use #pragma once.

An example header file, MyClass.h, using non-standard #pragma once:

// MyClass.h

#pragma once

// Your header contents goes here

Note that #pragma once is not standard, so it will make your code less portable. However, it does use less code, and can avoid name clashes.

Upvotes: 1

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29233

If myheader.h has what we call an include guard, then it will usually #define a macro with a name like MYHEADER_H. So first check whether your header file has this kind of thing.

If it does, you can check at any point whether it has been included (up to that point), using the #ifdef and #ifndef directives.

Upvotes: 0

Related Questions