gpt4 book ai didi

c++ - 一次包含已在 main.obj 中定义的 .h 函数

转载 作者:行者123 更新时间:2023-12-02 09:59:19 24 4
gpt4 key购买 nike

好的,简单地说:我已经将一个 .h 包含到另一个 .h 中,我收到一个编译错误,告诉我函数已经在 main.obj 中定义
但是,我只包含了一次 Graphics.h,那么 main.obj 怎么可能也定义了 Graphics.h 函数呢?
我收到错误 LNK2005“已在 main.obj 中定义”。
Graphics.h 包含许多其他文件需要的功能,但目前我们只有一个文件有问题,所以我想先解决这个问题。
编辑:已解决通过拆分标题,我保留了函数原型(prototype)的标题,并为函数定义创建了一个新的 Graphics.cpp
以下是最受关注的文件,我已对文件内容进行了注释,以便于阅读。
如果我评论错了,请告诉我,我会把它放在 pastebin 或类似的东西上
主文件

#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
图形.h 文件:
#ifndef GRAPHICS_H
#define GRAPHICS_H

#include "SFML/Graphics.hpp"

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

#endif // !GRAPHICS_H

最佳答案

您没有提供最小的可重现示例,但我最好的猜测是,您实现了一些功能 在头文件 , 而最终在多个 cpp 文件中直接或间接地包含该 header 。结果是具有完全相同签名的完全相同的函数,在两个 cpp 文件中编译,这导致链接器提示。
解决方案:

  • 将函数从头文件中移出并放入它自己的 cpp 文件中(可能是最好的)
  • 找到一种仅在一个 cpp 文件中包含 header 的方法(如果 header 不是您的并且您不想触摸它,则可能是第二好的)
  • 使该功能inline (可能是最简单的,但从技术上讲是最糟糕的)
  • 关于c++ - 一次包含已在 main.obj 中定义的 .h 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63499149/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com