简体   繁体   English

避免多重包含 c++

[英]Avoiding multiple includes c++

My header files are structured as follows我的 header 文件结构如下

                  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其中utilities.h仅包含函数和parameters.h 。h 包含 class 和 function 模板以及它们的类型指定定义,即

// 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 . kernels.h文件需要参数中的模板和utilities.h中的函数,但是两者都依赖于base.h How do I avoid importing base.h in either utilities.h or parameters.h ?如何避免在utilities.hparameters.h中导入base.h Rather, whats an efficient way to import?相反,什么是有效的导入方式?

cross platform you do include guards like this.跨平台你确实包括这样的守卫。

parameters.h参数.h

#ifndef PARAMETERS_H
#define PARAMETERS_H

... your header stuff here ...

#endif

MSVC (and most other compilers) also allow for MSVC(和大多数其他编译器)也允许

#pragma once

at the top of the header. And it will also insure the header is only included once.在 header 的顶部。它还将确保 header 仅包含一次。

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.两者都有助于避免问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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