Qt名称空间重复ID错误

时间:2011-10-20 20:03:14

标签: c++ qt

我希望这不是一个太具体的问题......但如果你能提供帮助我真的很感激!

当我构建我的应用程序时,我得到了这个错误,你知道为什么吗?:

ld: duplicate symbol colors::white      in mainwindow.o and main.o
collect2: ld returned 1 exit status

以下是主要的定义:

#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

这是主窗口的定义:

#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    glwidget = new MyGLBox(ui->centralWidget);
    startTimer(11);

//test frame
    BasicShapes shapes;

    Polygon3 square = shapes.create_square(V3(0.,0.,0.),V3(1.0,1.0,1.),colors::cyan);
    Polygon3 cube = shapes.create_cube(V3(-1.,-1.,-1.),V3(1.,1.,1.),colors::purple);
    Polygon3 triangle = shapes.create_triangle(V3(0,1.,0),V3(1.,1.,1.),5.,colors::green);
    //other stuff...

    ui->vLayoutGLview->addWidget(glwidget); //add the glwidget to the ui framework 
}

colors是文件colors.h中定义的命名空间:

namespace colors{
Color white(1.,1.,1.,0.);
Color black(0.,0.,0.,0.);
Color red(1.,0.,0.,0.);
Color green(0.,1.,0.,0.);
Color blue(0.,0.,1.,0.);
Color yellow(1.,1.,0.,0.);
Color purple(1.,0.,1.,0.);
Color cyan(0.,1.,1.,0.);
}

这是我的文件列表:

colors.h

#include <string>
#include <iostream>
#include <sstream>

mainwindow.h

#include <QMainWindow>
#include "myglbox.h"
#include "sceneobject.h"

mathvector.h

#include <vector>
#include <cmath>
#include <string>
#include <iostream>
#include <sstream>    
#include "colors.h"

myglbox.h

#include <QGLWidget>
#include <QtOpenGL>
#include <vector>
#include "mathvector.h"

sceneobject.h

#include "mathvector.h"

我很确定我没有在同一个文件中包含两次(但也许我错过了),无论如何,标题都受到标题保护的保护。

你知道我为什么会出现重复的id错误吗?如果没有命名空间,它编译得很好,但是带有标准颜色的命名空间真的很有用......

1 个答案:

答案 0 :(得分:5)

头文件中定义的对象将在包含该头的每个编译单元中重复,从而导致重复的定义错误。这些应该是extern(并在其他地方定义),或者(我的偏好)被制成自由函数:

Colors.h

namespace color
{
    const Color& white();
    const Color& black();
    // etc...
}

Colors.cpp

#include "colors.h"

namespace color
{
    const Color& white()
    {
       static Color w(1.,1.,1.,0.);
       return w;
    }

    const Color& black()
    {
       static Color b(0., 0., 0., 0.);
       return b;
    }
}

然后您可以轻松地使用它们:

Color white_copy = colors::white();
const Color& black = colors::black();