LNK2005错误.看起来一个文件被包含了两次

error LNK2005. It looks like a file is includet twice

本文关键字:两次 包含 一个 看起来 错误 LNK2005 文件      更新时间:2023-10-16

我想用OpenGL写一个小游戏,我有一个FileUtils.hppReadFile -函数,我有一个类ShaderProgram处理着色器和使用FileUtils

现在,当我想启动程序时,我得到这个错误:

ShaderProgram。obj:错误LNK2005: " class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl ReadFile(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &) " (?ReadFile@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABV12@@Z)已经定义在Main.obj

我对c++没有太多的经验,但我认为这个错误告诉我,我的ReadFile函数被定义了两次。如果您两次包含一个头文件,而该头文件没有#pragma once或header-guard,则会发生这种情况。

我的FileUtils.hpp是这样的:

#pragma once  
#include <string>
#include <iostream>
#include <fstream>
std::string ReadFile(const std::string& fileName)
{
    // File reading is done here.
    // Not important for this question.
}

我的ShaderProgram包含这个头:

#pragma once
#include <string>
#include <GLEWglew.h>
#include "FileUtils.hpp"
// Shader stuff done here

我的Main.cpp包括ShaderProgram.hpp:

#include "ShaderProgram.hpp"
#include "Window.hpp"
#define WIDTH 800
#define HEIGHT 600
#define TITLE "Voxelworld"
#define VERTEX_SHADER_FILE "voxelworld.v.glsl"
#define FRAGMET_SHADER_FILE "voxelworld.f.glsl"
using namespace voxelworld;
int main(int argc, char *argv[])
{
    Window window = Window(WIDTH, HEIGHT, TITLE);
    ShaderProgram shaderProgram = ShaderProgram(VERTEX_SHADER_FILE, FRAGMET_SHADER_FILE);
    while (!window.IsCloseRequested())
    {
        shaderProgram.Use();
        window.Update();
        shaderProgram.StopUse();
    }
    return 0;
}

Window.hpp既不包括FileUtils.hpp也不包括ShaderProgram.hpp

我很确定我只是在某个地方犯了一个愚蠢的错误,但我不知道在哪里。

除非函数足够小,可以内联(在这种情况下你应该这样标记),否则不要在头文件中定义函数,只有声明它们。

所以在头文件中,例如

std::string ReadFile(const std::string& fileName);

然后在一个源文件中做完整的定义:

std::string ReadFile(const std::string& fileName)
{
    ...
}

现在的问题是,该函数将在包含头文件的所有源文件(翻译单元)中定义。

没有类或命名空间包装,ReadFile可能与WinBase.h中的ReadFile冲突。WinBase.h经常在你的include树的深处结束。