Namespaces and includes generate link error

后端 未结 3 1808
忘了有多久
忘了有多久 2021-01-24 04:47

I was playing around with namespaces when I encountered a lnk2005 error. I can\'t figure out how to get around the error. Here\'s the error:

1>Source.obj :          


        
相关标签:
3条回答
  • 2021-01-24 05:45

    If you define any objects in a header file and include that header file in multiple translation units, those objects are now defined multiple times. This is the problem you're having. The declarations of t, l, and d introduce objects and you have done so in a header file.

    The proper method for supporting namespace scope variables is to declare them as extern in the header file. This makes them declarations only and not definitions. Then, in a single implementation file, define them.

    Change Chart.h to:

    #pragma once
    
    #include "foo.h"
    
    namespace Chart
    {
        extern int t;
    
        extern foo l;
    
        namespace Bars
        {
    
            extern int d;
        }
    
    }
    

    Then in an implementation file, perhaps Chart.cpp, do:

    int Chart::t;
    foo Chart::t;
    int Chart::Bars::d;
    
    0 讨论(0)
  • 2021-01-24 05:47

    I've had the exact same problem and I found a workarroud.

    chart.h becomes:

    #pragma once
    
    #include "foo.h"
    
    class Chart{
        static int t;
        static foo l;
        class Bars
        {
            static int d;
        };
    };
    

    and define the variables in chart.cpp

    int Chart::t;
    foo Chart::l;
    int Chart::Bars::d;
    

    Ugly, I know, but at least the syntax is the same wherever you need to use the vars.

    This way only ONE .obj file is created containing the variables which prevents the multiple definition erros.
    I haven't tried if you can declare a static variable on a namespace which could solve the problem.

    Edit:

    P.S. this solution gives some weird errors on msvc, as if every time it is included, sections of the code reference differente variables

    Tested on my own program the static-inside-namespace and it seems to work.
    Example.h:

    namespace sdl{
        static SDL_Surface* screen;
    
        static int xres = 640;
        static int yres = 480;
        static int bpp  = 32;
        static int flags = SDL_ASYNCBLIT;
    
    };
    
    0 讨论(0)
  • 2021-01-24 05:49

    Everywhere you're including Chart.h, you're effectively dropping variables t, l, and d into those objects. Declare them as extern, then define them in Chart.cpp

    0 讨论(0)
提交回复
热议问题