编译OpenGL着色器会导致语法错误

use*_*893 1 c++ opengl shader

我有两个简单的着色器(顶点和片段)

顶点着色器

#version 330 core

//=============================================
//---[Structs/Vertex Data]---------------------
//=============================================

layout(location = 0) in vec3 vertexPosition_modelspace;

//=============================================
//---[Variables]-------------------------------
//=============================================

uniform mat4 projection;
uniform mat4 view;

//=============================================
//---[Vertex Shader]---------------------------
//=============================================

void main()
{
   gl_Position = projection * view * vertexPosition_modelspace;
}
Run Code Online (Sandbox Code Playgroud)

片段着色器

#version 330 core

//=============================================
//---[Output Struct]---------------------------
//=============================================

out vec3 colour;

//=============================================
//---[Fragment Shader]-------------------------
//=============================================

void main()
{
    colour = vec3(1, 0, 0);
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试编译它们,我得到以下错误

错误C0000:语法错误,意外$ undefined,在令牌"undefined"处期待"::"

我相信这可能与我阅读文件的方式有关.以下是顶点着色器文件的示例

std::string VertexShaderCode = FindFileOrThrow(vertex_file_path);
std::ifstream vShaderFile(VertexShaderCode.c_str());
std::stringstream vShaderData;
vShaderData << vShaderFile.rdbuf();
vShaderFile.close();
Run Code Online (Sandbox Code Playgroud)

然后使用编译该文件

char const *VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
glCompileShader(VertexShaderID);
Run Code Online (Sandbox Code Playgroud)

如何有效地读取文件并避免这些错误?

编辑:

正确编译:

const std::string &shaderText = vShaderData.str();
GLint textLength = (GLint)shaderText.size();
const GLchar *pText = static_cast<const GLchar *>(shaderText.c_str());
glShaderSource(VertexShaderID, 1, &pText, &textLength);
glCompileShader(VertexShaderID);
Run Code Online (Sandbox Code Playgroud)

Nic*_*las 6

VertexShaderCode是你的文件名,而不是着色器字符串.那还在vShaderData.您需要将字符串复制出来vShaderData并将其输入glShaderSource.