一次包含了已经在main.obj

问题描述

好吧,简单地说:我在另一个.h中包含了一个.h,并且出现编译错误,告诉我该函数已经在main.obj中定义了。 但是,好吧,我只包含Graphics.h一次,那么main.obj怎么也定义了Graphics.h函数呢? 我收到一个错误LNK2005“已在main.obj中定义”。

Graphics.h包含许多其他文件将需要的功能,但是目前我们仅对一个文件存在问题,因此我想先对其进行修复。

编辑:已解决,通过拆分标题,我保留了函数原型的标题,并为函数定义创建了一个新的Graphics.cpp

这是最相关的文件,我对文件的内容进行了评论,以使文件易于阅读。 如果我的评论有误,请告诉我,然后将其放在pastebin或类似的东西上

main.cpp

#include "main.h"

using namespace std;

int main()
{
    sMainData data = {};
    main_Initialize(data);

    while (data.config.window.isOpen())
    {
        main_Event(data);
        main_Update(data);
        main_Draw(data);
    }
    return 0;
}

main.h文件:

#ifndef MAIN_H
#define MAIN_H

#include <SFML/Graphics.hpp>
#include "PlayerClass.h"

// Structures...
// Prototypes...
// Functions...

#endif // !MAIN_H

PlayerClass.h文件:

#ifndef PLAYERCLASS_H
#define PLAYERCLASS_H

#include "AliveClass.h" // Including the mother

#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>
#include "Graphics.h" // <-- So here we have our man

//Class definition

#endif // !1

Graphics.h文件:

#ifndef GRAPHICS_H
#define GRAPHICS_H

#include "SFML/Graphics.hpp"

// Prototypes...
// Functions...

#endif // !GRAPHICS_H

解决方法

您没有提供一个最小的可复制示例,但是我最大的猜测是,您已经在头文件中实现了一些功能,而最终直接或间接地包含了该头,多于一个cpp文件。结果是在两个cpp文件中编译的具有完全相同签名的功能完全相同,这导致链接器抱怨。

解决方案:

  • 将函数移出标头并移入其自己的cpp文件(可能是最好的)
  • 找到一种仅将标头包含在单个cpp文件中的方法(如果标头不属于您并且您不想触摸它,可能是第二好方法)
  • 使该功能inline(可能最简单,但技术上最差)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...