c++ - Qt命名空间重复id错误

标签 c++ qt

我希望问题不是太具体...但如果您能提供帮助,我将非常感激!

当我构建我的应用程序时出现此错误,你知道为什么吗?:

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

这里是main的定义:

#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.);
}

这是我的文件列表:

颜色.h

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

主窗口.h

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

数学 vector .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"

场景对象.h

#include "mathvector.h"

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

您知道为什么我会收到重复 ID 错误吗?没有 namespace 它编译得很好,但是具有标准颜色的 namespace 将非常有用...

最佳答案

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

颜色.h

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

颜色.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();

关于c++ - Qt命名空间重复id错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7841571/

相关文章:

c++ - 从参数列表生成 C++ 函数

c++ - qmenu 不适用于 MAC (Qt Creator)

c++ - 用嵌入式私有(private)类覆盖 Qt 类

qt - 嵌入在可执行文件中的Qt图标

c++ - 如何在 C++ 中将数字与数字分开?

c++ - 如何使用 std::chrono 调用本地时间和本地时间加 X 小时

c++ - 是否可以使模板特化等于另一种类型

c++ - 是否存在阻止采用D范围的C++语言障碍?

c++ - QT ButtonGroup 和可检查的按钮 : how to connect toggled signal with int and bool?

c - 分配 :what can "corrupt" allocated memory in Linux/Qt application (threads involved)?