我正在开发一个我在其他项目中使用的库,我有以下头文件:
#pragma once
#include <iostream>
#include <map>
#include "my_library/core/Structures.h"
namespace My_Library
{
namespace NodeReaders
{
namespace HumanReadable
{
char charBuffer[256];
unsigned int uintBuffer;
unsigned long long microsecondBuffer;
unsigned int getNextUInt(std::istream & is)
{
/// Implementation
}
unsigned long getNextMicroseconds(std::istream & is)
{
/// Implementation
}
...
}; // namespace HumanReadable
}; // namespace NodeReaders
}; // namespace My_Library
我试图将它包含在几个不同的源文件中,但每当我这样做时,我都会收到一个错误,指出这里定义的每个使用的函数都有一个重复的符号。为什么我会收到重复符号错误? #pragma once
难道不应该让它不会发生吗?
编辑:错误信息片段:
duplicate symbol __ZN8My_Library11NodeReaders13HumanReadable10uintBufferE in:
obj/project/Debug/ParseDriver.o
obj/project/Debug/ParseService.o
最佳答案
#pragma once
确保头文件在它包含的每个翻译单元中只包含一次。因此,如果您将它包含在多个 cpp 文件中,您将获得多个实现。
声明你的函数 inline
例如:
inline unsigned int getNextUInt(std::istream &is)
{
...
}
或者,将函数实现放在一个 cpp 文件中。
变量必须在 cpp 文件中定义。在头文件中,您将拥有:
extern unsigned int uintBuffer;
在 cpp 文件中你有这个:
unsigned int uintBuffer;
当您使用类而不是全局变量和函数时,所有这一切都会变得更容易。
关于c++ - 嵌套命名空间中的重复符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54658343/