嵌套名称空间中的重复符号 [英] Duplicate Symbol in nested namespace

查看:58
本文介绍了嵌套名称空间中的重复符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在其他项目中使用的库上工作,并且具有以下头文件:

I am working on a library that I'm using in my other projects and I have the following header file:

#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一次这样做是为了做到这一点?

I've tried to include it in a couple of different source files, but whenever I do, I get an error that there is a duplicate symbol for each of the used functions defined here. Why am I getting a duplicate symbol error? Isn't #pragma once supposed to make it so that that doesn't happen?

错误消息摘要:

duplicate symbol __ZN8My_Library11NodeReaders13HumanReadable10uintBufferE in:
    obj/project/Debug/ParseDriver.o
    obj/project/Debug/ParseService.o

推荐答案

#pragma一次确保标头文件在包含的每个翻译单元中仅包含一次.因此,如果将其包含在一个以上的cpp文件,您将获得多种实现.

#pragma once makes sure the header file is only included once in each translation unit it's included in. So if you include it in more than one cpp file, you will get multiple implementations.

声明您的函数内联,例如:

inline unsigned int getNextUInt(std::istream &is)
{
    ...
}

或者,将函数实现放在一个cpp文件中.

Or, put the function implementations in a cpp file.

必须在cpp文件中定义变量.在头文件中,您将拥有以下内容:

The variables have to be defined in a cpp file. In the header file, you will have this:

extern unsigned int uintBuffer;

,在cpp文件中,您有以下内容:

and in the cpp file you have this:

unsigned int uintBuffer;


当您使用类而不是全局变量和函数时,所有这些将变得更加容易.


All of this becomes easier when you use classes instead of global variables and functions.

这篇关于嵌套名称空间中的重复符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆