【问题标题】:Why does including a header-only file in another header file included somewhere else cause redefinition?为什么在其他地方包含的另一个头文件中包含仅头文件会导致重新定义?
【发布时间】:2021-12-24 20:37:06
【问题描述】:

我有一个仅包含标头的库,我们称之为foo.h,它包含在bar.h 中,它还包含在foobar.h 中。链接器抛出 LNK2005 错误,指出来自 foo.h 的函数和结构已在 foobar.obj 中定义。

foo.h 文件如下所示:

#pragma once

#ifndef  FOO 
#define FOO

//few structs and functions declarations and definitions (these aren't static nor inline) inside a namespace
#endif
//include guards added after I got the error for the first time

bar.h 看起来像这样:

#include "foo.h"
//some other code

foobar.h 看起来像这样:

#include "bar.h"
//some other code

这个问题可能是重复的:Why aren't include guards or pragma once working?

但是,除了使这些函数内联或静态之外,还有其他方法可以解决这个问题吗?也许根本不需要编辑foo.h

【问题讨论】:

    标签: linker linker-errors


    【解决方案1】:

    bar.hfoobar.h 很可能包含在多个文件中。

    最好的解决方案是将文件中的所有函数/方法声明为inline。你也可以声明它们static(或者,在 C++ 的情况下,将它们放入匿名命名空间中),但这效率较低,因为代码会重复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-17
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 2018-11-25
      • 2010-11-25
      • 1970-01-01
      相关资源
      最近更新 更多