LNK2005错误.看起来一个文件被包含了两次
error LNK2005. It looks like a file is includet twice
我想用OpenGL写一个小游戏,我有一个FileUtils.hpp
与ReadFile
-函数,我有一个类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树的深处结束。
- g++的分段错误(在NaN上使用to_string两次时)
- 蛇在C++不会连续转两次
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 我应该如何去缓解两次出现的cin?
- Realloc 两次无法在 Visual Studio 上运行
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- C++析构函数调用两次,堆栈分配的复合对象
- 为什么参数在构造 std::thread 时移动两次
- Qt插槽调用了两次
- 做 std::用相同的unique_ptr移动两次
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 如何使用预处理器指令包含两次具有不同代码的文件?
- 为什么在 C++ 中,当对象包含在另一个对象中时,复制构造函数被调用两次
- 尽管 #ifndef,但包含两次头文件
- Eclipse c++包含头两次错误
- 错误LNK2005:已经定义了包含头文件两次
- 为什么同一个头文件必须包含两次?
- LNK2005错误.看起来一个文件被包含了两次