Namespaces and includes generate link error

家住魔仙堡 提交于 2019-12-02 08:13:53

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;

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

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;

};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!