Search code examples
c++namespacesheader-files

Duplicate Symbol in nested namespace


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

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?

Edit: Snippit of error message:

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

Solution

  • #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.

    Declare your functions inline e.g. :

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

    Or, put the function implementations in a cpp file.


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

    extern unsigned int uintBuffer;
    

    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.