C++编译器在一个源文件中的一个函数调用中引发错误,但在具有相同函数调用的另一个源文件中不会引发错误

C++ compiler raises an error in one function call in one source file but not in another source file with the same function call

本文关键字:源文件 错误 一个 函数调用 另一个 C++ 编译器      更新时间:2023-10-16

我有两个C++源文件,它们的代码中有以下代码片段。

...
unsigned int triangleVaos[] = { 0, 0 };
unsigned int triangleVbos[] = { 0, 0 };
unsigned int numTriangleVaos = sizeof(triangleVaos) / sizeof(*triangleVaos);
unsigned int numTriangleVbos = sizeof(triangleVbos) / sizeof(*triangleVbos);
for (int index = 0; index < numTriangleVaos; index++) {
    unsigned int* triangleVao = &triangleVaos[index];
    glGenVertexArrays(1, triangleVaos);
    glBindVertexArray(triangleVao);
    ...
...

我正在编译源文件:

g++ -g 
    -std=c++11 
    -I include/ 
    -o src/1-getting-started/exer-hello-triangle-3 
    src/1-getting-started/exer-hello-triangle-3.cpp src/utils/glad.c 
    -lglfw -lGL -lX11 -lpthread -lXrandr -lXi -ldl;

当我编译第一个源文件时,一切正常。但是,每当我编译第二个源文件时,我都会收到以下错误消息:

src/1-getting-started/exer-hello-triangle-3.cpp: In function ‘int main()’:
src/1-getting-started/exer-hello-triangle-3.cpp:156:38: error: invalid conversion from ‘unsigned int*’ to ‘GLuint {aka unsigned int}’ [-fpermissive]
     glBindVertexArray(triangleVao);

这迫使我将第二个源文件中的代码片段修改为:

...
for (int index = 0; index < numTriangleVaos; index++) {
    unsigned int* triangleVao = &triangleVaos[index];
    glGenVertexArrays(1, triangleVaos);
    glBindVertexArray(*triangleVao);
...

编译第二个源文件现在成功。

为什么会这样?

(这个答案存在,以防有人偶然发现这个问题。

事实证明,我错误地设置了编译命令(我正在使用make(。第一个源文件的编译命令设置为编译不同的(但无错误的(源文件,这会导致编译成功。第二个源文件的编译命令正确设置为编译第二个源文件,该文件存在错误,因此无法编译。

这里的课程是确保正确设置编译命令以编译要编译的文件。一个被忽视的简单错误可能会在以后引起巨大的问题。

相关文章: