c++include-guards

Avoiding multiple includes c++


My header files are structured as follows

                  base.h
                 /      \
                /        \
       utilities.h       parameters.h
               \           /
                \         /
                 kernels.h
                    

Where utilities.h consists only of functions and parameters.h consists of class and function templates alongside their type specified definitions i.e.

// In parameters.h

// Function templates
template<typename T>
T transform_fxn(const T& value, std::string& method) { T a; return a; }
template<>
int transform_fxn(const int& value, std::string& method){
    .....   
}
template<>
double transform_fxn(const double& value, std::string& method){
    .....
}


// Class templates
template<typename T>
class BaseParameter {
    .....
}

template <typename T>
class Parameter;

template<>
class Parameter<double> : public BaseParameter<double> {
    .....
}
template<>
class Parameter<int> : public BaseParameter<int> {
    .....
}

The kernels.h file requires both templates in parameters and functions in utilities.h, however both are dependent on base.h. How do I avoid importing base.h in either utilities.h or parameters.h? Rather, whats an efficient way to import?


Solution

  • It seems to be not possible to avoid include headers several times, because you need usualy to include headers which are needed by the source code. But you can use include guards. There are two kinds of it:

    #ifndef BASE_H
      #define BASE_H
    
    ... <your code>
    
    #endif
    

    or another method is the following:

    #pragma once
    

    Both are helpfull to avoid problems.