在我的 C++ 代码中的多个 header 中包含一个 header

Including a header in multiple headers in my C++ code

我想在我的代码中包含 Numerical Recipes 一书中的 header 文件。我必须包含的 header 文件是 nr3.hpp 和 interp_1d.hpp。 interp_1d 需要 nr3 的定义才能工作。

我将编写出现在 interp_1d.hpp 上的一些代码,以便您了解我正在处理 interp_1d 代码的内容:

struct Base_interp{
...
};
Int Base_interp::locate(const Doub x){
...
}
...
Doub BaryRat_interp::interp(Doub x){
...
}

此 header 文件中没有 header 守卫。结果,当我尝试在多个其他 header 文件中输入它时,出现错误“66 个重复的体系结构符号 x86_64”。

我的代码结构如下:

myPulse.hpp:
#include "nr3.hpp"
#include "interp_1d.hpp"

calc1.hpp:
#include "myPulse.hpp"

calc2.hpp:
#include "myPulse.hpp"

main.cpp:
#include "myPulse.hpp"
#include "calc1.hpp"
#include "calc2.hpp"
#include "nr3.hpp"
#include "interp_1d.hpp"

我不知道如何解决这个问题。我希望能够在代码的多个部分中使用 interp_1d.hpp 函数。我尝试包括 header 个警卫,但这没有用:

#ifndef Interp_1d
#define Interp_1d

#endif

有谁知道我如何在多个其他 header 中使用 interp_1d header 而不会出现此错误?

在处理单个文件(或为书籍的简洁起见)时,可以简化一些代码,但 multi-file 大小写错误。

在你的情况下,缺少 header 守卫,并且缺少 inline(或放置定义的 cpp 文件)。

所以你不能使用它们as-is。

你有:

  • header/cpp 文件的拆分代码:

    // interp_1d.hpp
    #pragma once // or include guards
    struct Base_interp{
    //...
    };
    
    //interp_1d.cpp
    #include "interp_1d.hpp"
    Int Base_interp::locate(const Doub x){
    //...
    }
    
    Doub BaryRat_interp::interp(Doub x){
    //...
    }
    
  • 或放置额外的inline/static(虽然并不总是enough/possible(例如全局变量))和header guard.

    // interp_1d.hpp
    #pragma once // or include guards
    struct Base_interp{
    //...
    };
    
    inline Int Base_interp::locate(const Doub x){
    //...
    }
    
    inline Doub BaryRat_interp::interp(Doub x){
    //...
    }