避免多个包含 c++

Avoiding multiple includes c++

我的头文件结构如下

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

其中 utilities.h 仅包含函数,parameters.h 包含 class 和函数模板以及它们的类型指定定义,即

// 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> {
    .....
}

kernels.h 文件需要参数中的模板和 utilities.h 中的函数,但是两者都依赖于 base.h。如何避免在 utilities.hparameters.h 中导入 base.h?相反,什么是有效的导入方式?

跨平台你确实包括这样的守卫。

parameters.h

#ifndef PARAMETERS_H
#define PARAMETERS_H

... your header stuff here ...

#endif

MSVC(和大多数其他编译器)也允许

#pragma once

在 header 的顶部。它还将确保 header 仅包含一次。

似乎无法避免多次包含headers,因为您通常需要包含源代码需要的headers。但是你可以使用包括守卫。有两种:

#ifndef BASE_H
  #define BASE_H

... <your code>

#endif

或另一种方法如下:

#pragma once

两者都有助于避免问题。