使用 g++ 的 OpenGL 代码的编译问题

use*_*759 5 c++ opengl g++

当我尝试使用 gcc 使用以下命令编译用 c 语言编写的 opengl 代码时,它运行良好:

\n\n
gcc -Wall tutorial10.c -lGL -lglut -lGLU\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是当我尝试使用 g++ 进行相同的编译时

\n\n
g++ -Wall tutorial10.c -lGL -lglut -lGLU\n
Run Code Online (Sandbox Code Playgroud)\n\n

它开始给出很多这样的错误:

\n\n
tutorial10.c: In function \xe2\x80\x98void drawRect()\xe2\x80\x99:\ntutorial10.c:28:34: error: \xe2\x80\x98glClearBufferfv\xe2\x80\x99 was not declared in this scope\ntutorial10.c:34:28: error: \xe2\x80\x98glUseProgram\xe2\x80\x99 was not declared in this scope\ntutorial10.c:36:24: error: \xe2\x80\x98glGenBuffers\xe2\x80\x99 was not declared in this scope\ntutorial10.c:37:37: error: \xe2\x80\x98glBindBuffer\xe2\x80\x99 was not declared in this scope\ntutorial10.c:47:71: error: \xe2\x80\x98glBufferData\xe2\x80\x99 was not declared in this scope\ntutorial10.c:49:52: error: \xe2\x80\x98glVertexAttribPointer\xe2\x80\x99 was not declared in this scope\ntutorial10.c:50:29: error: \xe2\x80\x98glEnableVertexAttribArray\xe2\x80\x99 was not declared in this scope\ntutorial10.c:52:60: error: \xe2\x80\x98glGetUniformLocation\xe2\x80\x99 was not declared in this scope\ntutorial10.c:54:42: error: \xe2\x80\x98glUniform4f\xe2\x80\x99 was not declared in this scope\ntutorial10.c:59:30: error: \xe2\x80\x98glDisableVertexAttribArray\xe2\x80\x99 was not declared in this scope\ntutorial10.c: In function \xe2\x80\x98int main(int, char**)\xe2\x80\x99:\ntutorial10.c:93:34: error: \xe2\x80\x98glCreateProgram\xe2\x80\x99 was not declared in this scope\ntutorial10.c:95:54: error: \xe2\x80\x98glCreateShader\xe2\x80\x99 was not declared in this scope\ntutorial10.c:124:76: error: \xe2\x80\x98glShaderSource\xe2\x80\x99 was not declared in this scope\ntutorial10.c:128:36: error: \xe2\x80\x98glCompileShader\xe2\x80\x99 was not declared in this scope\ntutorial10.c:134:49: error: \xe2\x80\x98glAttachShader\xe2\x80\x99 was not declared in this scope\ntutorial10.c:136:29: error: \xe2\x80\x98glLinkProgram\xe2\x80\x99 was not declared in this scope\ntutorial10.c:147:35: error: \xe2\x80\x98glDeleteShader\xe2\x80\x99 was not declared in this scope\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

评论的标题:

\n\n
#include<stdio.h>\n#include<stdlib.h>\n#include<GL/glut.h>\n#include<malloc.h>\n#include<string.h>\n#include<math.h>\n
Run Code Online (Sandbox Code Playgroud)\n

kel*_*tar 4

您的翻译单元中没有 opengl 函数声明(很可能您没有包含<GL/gl.h>)。

gcc这样做是因为旧版本的 C 语言允许隐式声明 - 每当您使用函数时,gcc 都会自动使用通用规则声明它。这并不意味着函数将被正确调用 - 隐式规则非常通用,并且会导致float参数类型等问题,因此预计这里会出现很多错误。

如果您将-Wimplicit-function-declaration(或-Wall,其中包括此声明以及许多其他声明)添加到您的 cflags,您可以看到有关隐式声明的警告。

g++另一方面,启用了 C++ 模式,该模式禁止隐式声明。

总而言之,不要使用隐式声明,除非您真正理解它们的作用(但在这种情况下您无论如何都不想使用它们)。