简体   繁体   中英

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 ie

// 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?

cross platform you do include guards like this.

parameters.h

#ifndef PARAMETERS_H
#define PARAMETERS_H

... your header stuff here ...

#endif

MSVC (and most other compilers) also allow for

#pragma once

at the top of the header. And it will also insure the header is only included once.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM