-2

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?

lefe
  • 147
  • 1
  • 10
  • You tagged this `circular-dependency` but I don't see a circular dependency anywhere here. Are you looking for [include guards](https://stackoverflow.com/questions/8020113/c-include-guards/8020211)? – Nathan Pierson Aug 21 '21 at 14:49
  • 3
    What is the problem exactly? Double inclusion is usually not a problem, since it's prevented by include guards. – HolyBlackCat Aug 21 '21 at 14:49
  • Thanks couldnt find the write terms for this issue. include guards are the one. – lefe Aug 21 '21 at 14:53

2 Answers2

3

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.

Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19
3

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.