c++ - 嵌套命名空间中的重复符号

标签 c++ namespaces header-files

我正在开发一个我在其他项目中使用的库,我有以下头文件:

#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/

相关文章:

xml - XSD 属性前缀命名空间

xcode4 - Xcode 4 中使用静态库的 header 管理

c++ - 编译时动态链接库不生成 .lib 文件(Visual Studio C++ Express)

c++ - 当可插入的 Cocoa 应用程序仅公开 C++ API 时,如何在插件中显示一个窗口?

c++ - 如何将菜单从资源插入到现有菜单?

PHP - 命名空间无法正常工作

c++ - 搞乱封装

php - 需要在所有 Controller Laravel 的顶部包含输入

c++ - 结构类型 "does not provide a subscript operator"

java - 为什么 Objective-C 使用头文件而不是像 Java 那样使用单文件类?