2012-04-26 69 views
0

這不是代碼問題,因爲它編譯時我告訴編譯器將它編譯爲C,但是當我將設置設置爲默認(即將其編譯爲C++)時,它不會編譯。當我將它編譯爲C++時,我得到了許多錯誤,這些錯誤沿着「未定義的glClear引用」行。我正在使用Microsoft的Visual Studio C++編譯器。我有一切正確的鏈接。爲什麼我的opengl freeglut應用程序編譯爲C而不是C++?

的代碼是:

#include <GL/glut.h> 
#include <GL/freeglut.h> 
#include <GL/gl.h> 



void display(void) 
{ 
    /* Clear all pixels */ 
    glClear(GL_COLOR_BUFFER_BIT); 

    /* draw white polygon (rectangle) with 
    * corners at (0.25, 0.25, 0.0) and (0.75, 0.75, 0.0) 
    */ 

    glColor3f(1.0, 1.0, 1.0); 
    glBegin(GL_POLYGON); 
     glVertex3f(0.25, 0.25, 0.0); 
     glVertex3f(0.75, 0.25, 0.0); 
     glVertex3f(0.75, 0.75, 0.0); 
     glVertex3f(0.25, 0.75, 0.0); 
    glEnd(); 

    /* don't wait! 
    * start processing buffered OpenGL routines 
    */ 

     glFlush(); 
} 

void init(void) 
{ 
    /* Select clearing background color */ 
    glClearColor(0.0, 0.0, 0.0, 0.0); 

    /* Initialize viewing values */ 
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); 
} 


/* 
* Declare initial window size, position, and display mode 
* (single buffer and RGBA). Open window with 「hello」 
* in its title bar. Call initialization routines. 
* Register callback function to display graphics. 
* Enter main loop and process events. 
*/ 
int main(int argc, char** argv) 
{ 
    glutInit(&argc, argv); 
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); 
    glutInitWindowSize(250, 250); 
    glutInitWindowPosition(100, 100); 
    glutCreateWindow("hello"); 
    init(); 
    glutDisplayFunc(display); 
    glutMainLoop(); 
    return 0; /* ISO C requires main to return int. */ 
} 

此外,如果任何人有學習的OpenGL使用C++,你可以請推薦一下合適的資源?

+0

什麼是確切的錯誤?它是編譯錯誤還是鏈接錯誤? – Cameron 2012-04-26 03:23:58

+0

我得到一個錯誤,說, 未定義的引用gl 我知道我有一切正確的鏈接,因爲當我編譯它在C它的作品 – 2012-04-26 03:28:30

+5

*未定義的引用*是一個鏈接器錯誤。你包括opengl32.lib? – 2012-04-26 03:28:44

回答

2

很可能是因爲glClear沒有在當前包含的任何頭文件中聲明。在C語言中,未聲明的函數經常被假定爲基於它的參數具有某種類型,並返回一個int。所以當用C編譯時,你可能會得到一個關於它未聲明的警告(我希望你已經啓用了警告,並且在編譯時閱讀它們),但是它會盡力編譯和鏈接它。

C++對未聲明的函數更嚴格。

1

正如Alexadre Jasmin和Bart指出的那樣,請驗證您是否正確鏈接了OpenGL庫。我在Ubuntu上使用freeglut使用

-lGLU -lGL -lglut

如果這樣不能解決問題,請嘗試在cpp文件的頂部添加

#define GLUT_DISABLE_ATEXIT_HACK

相關問題