c++ - 宏守卫在 header 中不起作用

标签 c++

大家好,我得到了这样的代码:

//a.h 
#ifndef SB
#define SB
namespace A{ int a = 10; int b = 10;}
#endif

但是,如果我在 a.cpp 文件中导入 a.h,编译器会报错:

 error LNK2005: "int A::a" (?a@A@@3HA) already defined in a.obj

看起来编译器会将 .h 文件和 .cpp 文件组合在一起,而无需显式“导入”语句。但对我来说,定义宏守卫会发生这种情况是没有意义的。

我使用 Visual C++

最佳答案

#include 守卫防止一个文件多次包含同一个 .h 文件。它们不会阻止多个文件,每个文件都包含一次相同的 .h 文件,这就是我假设发生在您身上的情况。将您的定义移动到单个 .cpp 文件中,并在此处仅留下一个声明:

namespace A {
    extern int a;
    extern int b;
}

告诉编译器这些变量存在于某处,但它们的定义可以在别处找到。

关于c++ - 宏守卫在 header 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5439630/

相关文章:

c++ - 为什么来自 GetWindowRect(rcWindow2) 的 cx/cy 与馈入 OnSize 的 cx/cy 不同?

c++ - constexpr 的运行时错误

c++ - 为什么很多cache.h文件中使用 '#define alloc_nr(x) (((x)+16)*3/2)'宏?

c++ - 为什么在#include <string>之后仍需要使用std::string?

C++17 原子和 condition_variable 死锁

c++ - 如何使用 std::auto_ptr 作为函数的参数?

c++ - std::transform 一元操作签名

c++ - 全局访问 wxFrame(s) & wxDialog(s)

c++ - C++中深层继承树的性能影响

c++ - 包含 boost::numeric::ublas::matrix 的类的运算符重载