【问题标题】:Qt : multiple defined symbols foundQt:找到多个定义的符号
【发布时间】:2015-04-30 09:50:55
【问题描述】:

这是一个 Qt 项目,一旦构建,就会生成一个 dll AnTS_Core.dll 所以我有:

AnTs_Core.cpp

#include <windows.h>
#include "Globals.h" // my global values
extern "C"
{
    __declspec(dllexport) void load();
}
void load()
{

    mainDispatcher = new Dispatcher();
}

包含所有主要对象的全局头文件作为全局(因为我想从另一个对象调用对象方法):

Globals.h:

#ifndef GLOBALS_H
#define GLOBALS_H
#include "AnTS_Types.h"
#include "Dispatcher.h"
#ifdef __cplusplus
extern "C"
{
#endif
    Dispatcher *mainDispatcher;
#ifdef __cplusplus
}
#endif
#endif // GLOBALS_H

调度程序:头文件

#ifndef DISPATCHER_H
#define DISPATCHER_H
#include "AnTS_Types.h"
#include "Device.h"
#include <list>
#include <windows.h>
class Dispatcher
{
public:
    Dispatcher();
    ~Dispatcher();
private:
    std::list<Device*> _devices;
};
#endif

Dispatcher.cpp:

#include "Dispatcher.h"
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <string.h>
#include <dirent.h>
#include <regex>
#include "Device/DEV_Struct.h"
Dispatcher::Dispatcher()
{
}

和设备(Dispatcher 包含设备列表)

设备.h

#ifndef DEVICE_H
#define DEVICE_H

#include <windows.h>
#include "Device/DEV_Struct.h"
#include "AnTS_Types.h"
#define ANTS_DEVICE_NAME_LENGHT 64
class Device
{
public:
    Device(char*);
    ~Device();
};
#endif // DEVICE_H

设备.cpp

#include "../Includes/Device.h"
#include <string.h>
#include <iostream>
#include <cstdio>
#include "Globals.h"

Device::Device(char* dllPath)
{
}

错误是:

LNK2005 _mainDispatcher 已在 AnTS_Core.cpp.obj 中定义

LNK1169 找到一个或多个多重定义的符号

当我在 Device.cpp 中注释 #include "Globals.h" 行时,错误消失了。但我想从 device.cpp 文件中访问全局变量(例如访问其他 Dispatcher 或访问其他对象)。

【问题讨论】:

    标签: c++ qt symbols


    【解决方案1】:

    所以,这是一个经典的 declaration vs definition 问题 - 您已经在标头中定义了变量 mainDispatcher,因此包含此标头的每个编译单元最终都有一个定义,您想要在其中声明变量标头为extern(这只会通知包含标头的每个编译单元存在此类变量):

    #ifndef GLOBALS_H
    #define GLOBALS_H
    #include "AnTS_Types.h"
    #include "Dispatcher.h"
    #ifdef __cplusplus
    extern "C"
    {
    #endif
        extern Dispatcher *mainDispatcher;
    #ifdef __cplusplus
    }
    #endif
    #endif // GLOBALS_H`
    

    您应该将实际定义 Dispatcher* mainDispatcher 放在您的 .cpp 文件之一中。

    【讨论】:

    • 啊,非常感谢!我已经尝试过“extern”,但我没有将定义放在 .cpp 文件中。
    【解决方案2】:

    您的Globals.h 中有Dispatcher *mainDispatcher;,这样每个包含此标头的编译单元都会创建自己的此符号实例。在Globals.h 中声明extern Dispatcher *mainDispatcher;,并在AnTs_Core.cpp 中添加Dispatcher *mainDispatcher;。这样一来,AnTs_Core.cpp 编译单元就会有一个符号,而其他人将通过 extern 声明看到它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多