【问题标题】:Avoiding multiple includes c++避免多个包含 C++
【发布时间】:2021-08-21 14:47:28
【问题描述】:

我的头文件结构如下

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

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

// 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?相反,什么是有效的导入方式?

【问题讨论】:

  • 你标记了这个circular-dependency,但我在这里看不到循环依赖。你在找include guards吗?
  • 到底是什么问题?双重包含通常不是问题,因为它被包含保护所阻止。
  • 感谢您找不到此问题的书面条款。包括警卫就是其中之一。

标签: c++ include-guards


【解决方案1】:

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

#ifndef BASE_H
  #define BASE_H

... <your code>

#endif

或另一种方法如下:

#pragma once

两者都有助于避免问题。

【讨论】:

    【解决方案2】:

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

    参数.h

    #ifndef PARAMETERS_H
    #define PARAMETERS_H
    
    ... your header stuff here ...
    
    #endif
    

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

    #pragma once
    

    在标题的顶部。并且它还将确保标题只包含一次。

    【讨论】:

    • 实际上每个现代编译器都支持#pragma once,不仅仅是MSVC。
    • @HolyBlackCat 感谢您的反馈。 (我的一部分主要生活在 MSVC 世界中)
    • 考虑将此纳入您的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多