Ошибка сборки при попытке запустить пример OpenGL в VC

Чего я не могу понять, так это почему компилируются оба отдельных файла .cpp, но решение не создается. Код, который не компилируется, хотя я следую инструкциям это

// Two-Dimensional Sierpinski Gasket       
// Generated using randomly selected vertices and bisection



#include "Angel.h"
#include <GL/glut.h>
#include <GL/glew.h>

#pragma comment(lib, "glew32.lib")

const int NumPoints = 5000;

//----------------------------------------------------------------------------

void
init( void )
{

    vec2 points[NumPoints];

    // Specifiy the vertices for a triangle
    vec2 vertices[3] = {
        vec2( -1.0, -1.0 ), vec2( 0.0, 1.0 ), vec2( 1.0, -1.0 )
    };

    // Select an arbitrary initial point inside of the triangle
    points[0] = vec2( 0.25, 0.50 );

    // compute and store N-1 new points
    for ( int i = 1; i < NumPoints; ++i ) {
        int j = rand() % 3;   // pick a vertex at random

        // Compute the point halfway between the selected vertex
        //   and the previous point
        points[i] = ( points[i - 1] + vertices[j] ) / 2.0;
    }

    // Create a vertex array object
    GLuint vao;
    glGenVertexArrays( 1, &vao );
    glBindVertexArray( vao );

    // Create and initialize a buffer object
    GLuint buffer;
    glGenBuffers( 1, &buffer );
    glBindBuffer( GL_ARRAY_BUFFER, buffer );
    glBufferData( GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW );

    // Load shaders and use the resulting shader program
    GLuint program = InitShader( "vshader21.glsl", "fshader21.glsl" );
    glUseProgram( program );

    // Initialize the vertex position attribute from the vertex shader
    GLuint loc = glGetAttribLocation( program, "vPosition" );
    glEnableVertexAttribArray( loc );
    glVertexAttribPointer( loc, 2, GL_FLOAT, GL_FALSE, 0,
                           BUFFER_OFFSET(0) );

    glClearColor( 1.0, 1.0, 1.0, 1.0 ); // white background
}

//----------------------------------------------------------------------------

void
display( void )
{
    glClear( GL_COLOR_BUFFER_BIT );     // clear the window
    glDrawArrays( GL_POINTS, 0, NumPoints );    // draw the points
    glFlush();
}

//----------------------------------------------------------------------------

void
keyboard( unsigned char key, int x, int y )
{
    switch ( key ) {
    case 033:
        exit( EXIT_SUCCESS );
        break;
    }
}

//----------------------------------------------------------------------------

int
main( int argc, char **argv )
{

    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGBA );
    glutInitWindowSize( 512, 512 );

    // If you are using freeglut, the next two lines will check if 
    // the code is truly 3.2. Otherwise, comment them out

     glutInitContextVersion( 3, 1 );
     glutInitContextProfile( GLUT_CORE_PROFILE );

    glutCreateWindow( "Sierpinski Gasket" );




    glewInit();

    init();

    glutDisplayFunc( display );
    glutKeyboardFunc( keyboard );

    glutMainLoop();
    return 0;
}

Я получаю это странное сообщение об ошибке, когда пытаюсь собрать пример проекта с сайта OpenGL Эдварда Ангела:

1>------ Build started: Project: 6E test, Configuration: Release Win32 ------
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewBindBuffer
1>example1.obj : error LNK2001: unresolved external symbol __imp____glutCreateWindowWithExit@8
1>example1.obj : error LNK2001: unresolved external symbol __imp____glutInitWithExit@12
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewVertexAttribPointer
1>example1.obj : error LNK2001: unresolved external symbol __imp__glewInit@0
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewGenVertexArrays
1>example1.obj : error LNK2001: unresolved external symbol __imp__glutInitContextProfile@4
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewUseProgram
1>example1.obj : error LNK2001: unresolved external symbol __imp__glutInitContextVersion@8
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewBufferData
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewBindVertexArray
1>example1.obj : error LNK2001: unresolved external symbol __imp__glutInitDisplayMode@4
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewGetAttribLocation
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewGenBuffers
1>example1.obj : error LNK2001: unresolved external symbol __imp__glutKeyboardFunc@4
1>example1.obj : error LNK2001: unresolved external symbol __imp__glutMainLoop@0
1>example1.obj : error LNK2001: unresolved external symbol __imp__glutInitWindowSize@8
1>example1.obj : error LNK2001: unresolved external symbol __imp__glutDisplayFunc@4
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewEnableVertexAttribArray
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewCreateShader
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewGetShaderInfoLog
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewLinkProgram
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewCompileShader
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewShaderSource
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewGetProgramiv
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewGetShaderiv
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewGetProgramInfoLog
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewCreateProgram
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewAttachShader
1>C:\Users\student\Downloads\6E_example1_VC10\6E test\Release\6E test.exe : fatal error LNK1120: 29 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Мне кажется, что я пытался скомпоновать несовместимые библиотеки, на что вышеописанное похоже для вас? Полный исходный код, который я пытаюсь запустить (с Windows 7),

// Two-Dimensional Sierpinski Gasket       
// Generated using randomly selected vertices and bisection
#pragma comment(lib, "glew32.lib")
#include "Angel.h"

const int NumPoints = 5000;

//----------------------------------------------------------------------------

void
init( void )
{

    vec2 points[NumPoints];

    // Specifiy the vertices for a triangle
    vec2 vertices[3] = {
        vec2( -1.0, -1.0 ), vec2( 0.0, 1.0 ), vec2( 1.0, -1.0 )
    };

    // Select an arbitrary initial point inside of the triangle
    points[0] = vec2( 0.25, 0.50 );

    // compute and store N-1 new points
    for ( int i = 1; i < NumPoints; ++i ) {
        int j = rand() % 3;   // pick a vertex at random

        // Compute the point halfway between the selected vertex
        //   and the previous point
        points[i] = ( points[i - 1] + vertices[j] ) / 2.0;
    }

    // Create a vertex array object
    GLuint vao;
    glGenVertexArrays( 1, &vao );
    glBindVertexArray( vao );

    // Create and initialize a buffer object
    GLuint buffer;
    glGenBuffers( 1, &buffer );
    glBindBuffer( GL_ARRAY_BUFFER, buffer );
    glBufferData( GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW );

    // Load shaders and use the resulting shader program
    GLuint program = InitShader( "vshader21.glsl", "fshader21.glsl" );
    glUseProgram( program );

    // Initialize the vertex position attribute from the vertex shader
    GLuint loc = glGetAttribLocation( program, "vPosition" );
    glEnableVertexAttribArray( loc );
    glVertexAttribPointer( loc, 2, GL_FLOAT, GL_FALSE, 0,
                           BUFFER_OFFSET(0) );

    glClearColor( 1.0, 1.0, 1.0, 1.0 ); // white background
}

//----------------------------------------------------------------------------

void
display( void )
{
    glClear( GL_COLOR_BUFFER_BIT );     // clear the window
    glDrawArrays( GL_POINTS, 0, NumPoints );    // draw the points
    glFlush();
}

//----------------------------------------------------------------------------

void
keyboard( unsigned char key, int x, int y )
{
    switch ( key ) {
    case 033:
        exit( EXIT_SUCCESS );
        break;
    }
}

//----------------------------------------------------------------------------

int
main( int argc, char **argv )
{

    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_RGBA );
    glutInitWindowSize( 512, 512 );

    // If you are using freeglut, the next two lines will check if 
    // the code is truly 3.2. Otherwise, comment them out

     glutInitContextVersion( 3, 1 );
     glutInitContextProfile( GLUT_CORE_PROFILE );

    glutCreateWindow( "Sierpinski Gasket" );




    glewInit();

    init();

    glutDisplayFunc( display );
    glutKeyboardFunc( keyboard );

    glutMainLoop();
    return 0;
}


#pragma comment(lib, "glew32.lib")
#include "Angel.h"

namespace Angel {

// Create a NULL-terminated string by reading the provided file
static char*
readShaderSource(const char* shaderFile)
{
    FILE* fp = fopen(shaderFile, "r");

    if ( fp == NULL ) { return NULL; }

    fseek(fp, 0L, SEEK_END);
    long size = ftell(fp);

    fseek(fp, 0L, SEEK_SET);
    char* buf = new char[size + 1];
    fread(buf, 1, size, fp);

    buf[size] = '\0';
    fclose(fp);

    return buf;
}


// Create a GLSL program object from vertex and fragment shader files
GLuint
InitShader(const char* vShaderFile, const char* fShaderFile)
{
    struct Shader {
    const char*  filename;
    GLenum       type;
    GLchar*      source;
    }  shaders[2] = {
    { vShaderFile, GL_VERTEX_SHADER, NULL },
    { fShaderFile, GL_FRAGMENT_SHADER, NULL }
    };

    GLuint program = glCreateProgram();


    for ( int i = 0; i < 2; ++i ) {
    Shader& s = shaders[i];
    s.source = readShaderSource( s.filename );
    if ( shaders[i].source == NULL ) {
        std::cerr << "Failed to read " << s.filename << std::endl;
        exit( EXIT_FAILURE );
    }

    GLuint shader = glCreateShader( s.type );

    glShaderSource( shader, 1, (const GLchar**) &s.source, NULL );
    glCompileShader( shader );

    GLint  compiled;
    glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled );
    if ( !compiled ) {
        std::cerr << s.filename << " failed to compile:" << std::endl;
        GLint  logSize;
        glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logSize );
        char* logMsg = new char[logSize];
        glGetShaderInfoLog( shader, logSize, NULL, logMsg );
        std::cerr << logMsg << std::endl;
        delete [] logMsg;

        exit( EXIT_FAILURE );
    }

    delete [] s.source;

    glAttachShader( program, shader );
    }

    /* link  and error check */
    glLinkProgram(program);

    GLint  linked;
    glGetProgramiv( program, GL_LINK_STATUS, &linked );
    if ( !linked ) {
    std::cerr << "Shader program failed to link" << std::endl;
    GLint  logSize;
    glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logSize);
    char* logMsg = new char[logSize];
    glGetProgramInfoLog( program, logSize, NULL, logMsg );
    std::cerr << logMsg << std::endl;
    delete [] logMsg;

    exit( EXIT_FAILURE );
    }

    /* use program object */
    glUseProgram(program);

    return program;
}

}  // Close namespace Angel block

Обновлять

Я изменил код, чтобы начать, как показано ниже, и он все еще не собирается, и я все еще получаю сообщение об ошибке сборки.

#pragma comment(lib, "glew32.lib")
#define GLEW_STATIC 1
#include "Angel.h"
#include <GL\glew.h>

Обновление 150529

Я могу собрать примеры GLUT для freeglut, поэтому GLUT отображается правильно установленным с VC, но затем, когда я дважды щелкаю один из примеров, он говорит, что freeglut.dll не установлен в моей системе. Я все еще получаю ту же ошибку компиляции при попытке собрать пример Ангела. Почему? Что я делаю неправильно? Что я должен делать?

введите здесь описание изображения

1>------ Build started: Project: 6E test, Configuration: Release Win32 ------
1>  example1.cpp
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\Angel.h(65): warning C4305: 'initializing' : truncation from 'double' to 'const GLfloat'
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(698): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(699): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(700): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(721): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(723): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(726): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(742): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>  InitShader.cpp
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\Angel.h(65): warning C4305: 'initializing' : truncation from 'double' to 'const GLfloat'
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(698): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(699): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(700): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(721): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(723): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(726): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>c:\users\student\downloads\6e_example1_vc10\6e test\code\mat.h(742): warning C4244: '=' : conversion from 'double' to 'GLfloat', possible loss of data
1>..\CODE\InitShader.cpp(13): warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1>          C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\stdio.h(218) : see declaration of 'fopen'
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewBindBuffer
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewVertexAttribPointer
1>example1.obj : error LNK2001: unresolved external symbol __imp__glewInit@0
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewGenVertexArrays
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewUseProgram
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewBufferData
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewBindVertexArray
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewGetAttribLocation
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewGenBuffers
1>example1.obj : error LNK2001: unresolved external symbol __imp____glewEnableVertexAttribArray
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewCreateShader
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewGetShaderInfoLog
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewLinkProgram
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewCompileShader
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewShaderSource
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewGetProgramiv
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewGetShaderiv
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewGetProgramInfoLog
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewCreateProgram
1>InitShader.obj : error LNK2001: unresolved external symbol __imp____glewAttachShader
1>C:\Users\student\Downloads\6E_example1_VC10\6E test\Release\6E test.exe : fatal error LNK1120: 20 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Обновлять

Я попытался спросить об этом снова, и это все еще не сработает:

Ошибка компоновщика с glew и Visual Studio в Windows 7


person Niklas R.    schedule 05.05.2013    source источник


Ответы (2)


Вам не хватает GLEW (библиотека обработчика расширений OpenGL). Вы можете связать это со следующей прагмой где-нибудь в исходном коде:

#pragma comment(lib, "glew32.lib")

Или вы можете изменить флаги компоновщика в настройках проекта. Это предполагает, что у вас установлена ​​библиотека GLEW. В моей системе я установил его по следующему пути:

C:\Program Files (x86)/Microsoft Visual Studio 10.0/VC/lib/glew32.lib

Путь может быть другим в вашей системе, и есть другие способы связи с GLEW, если вы не хотите его устанавливать.

person Dietrich Epp    schedule 05.05.2013
comment
Спасибо за ответ. Я вставил прагму, и у меня есть файл в том месте, которое вы упомянули, но все равно получаю ту же ошибку. Что может быть сделано? - person Niklas R.; 06.05.2013
comment
@NickRosencrantz: Вы не забыли включить заголовки GLEW? - person Dietrich Epp; 06.05.2013
comment
Я могу включить только GL\glew.h, если это то, что вы имеете в виду, и тогда я все еще получаю сообщение об ошибке, когда добавляю строку #include <GL\glew.h> - person Niklas R.; 06.05.2013
comment
Убедитесь, что ваше определение для GLEW_STATIC соответствует определению, используемому для компиляции LibGLEW. Если вы используете статический GLEW, и библиотека, и исполняемый файл должны быть определены GLEW_STATIC. Если вы используете DLL, GLEW_STATIC не должно быть определено для обоих. - person Dietrich Epp; 06.05.2013
comment
Спасибо за комментарий, но я не понимаю, что это значит. Я не знаю, какое у меня определение для GLEW_STATIC, где оно находится и как найти LibGLEW. Это слишком много деталей, чтобы просто запустить пример кода. - person Niklas R.; 06.05.2013
comment
@NickRosencrantz: определение константы, используемой для компиляции библиотеки. Либо определили, либо нет. Если вы связываетесь со статическим LibGLEW, вы должны #define GLEW_STATIC 1 перед включением заголовков. Справляться с подобными вещами в Windows довольно сложно, но в этом вся прелесть. - person Dietrich Epp; 06.05.2013
comment
Проблема заключалась в том, что я смешал 64-битные и 32-битные библиотеки. Я начал использовать исключительно 32-битные библиотеки, а затем это продвинуло меня дальше, так что я могу связать, и вместо этого я теперь получаю только ошибку времени выполнения при попытке выполнить мой пример OpenGL. - person Niklas R.; 01.06.2013
comment
Рад слышать, что вы решили это. Кажется, что сообщения об ошибках могли бы быть более информативными — в OS X выдается сообщение об ошибке, как будто файл был создан для i386, который не является связанной архитектурой (x86_64). - person Dietrich Epp; 02.06.2013

Вы можете отпустить GLEW. Все, что он делает, это загружает расширения GL (и WGL). Тем не менее, вы можете сделать это самостоятельно:

1.включите заголовки (погуглите имена файлов для скачивания):

#include<GL/glext.h>
#include<GL/wglext.h>

2. объявить указатели функций:

PFNGLGENVERTEXARRAYSPROC glGenVertexArrays;
PFNGLBINDVERTEXARRAYPROC glBindVertexArray;
PFNWGLMAKECONTEXTCURRENTARBPROC wglMakeContextCurrentARB;
//etc.

3. загрузите указатели функций через wglGetProcAddress:

glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)wglGetProcAddress("glGenVertexArrays");
glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)wglGetProcAddress("glBindVertexArray");
wglMakeContextCurrentARB = (PFNWGLMAKECONTEXTCURRENTARBPROC)wglGetProcAddress("wglMakeContextCurrentARB");
//etc

4. Пусть код примера использует их (без изменений)!

glGenVertexArrays( 1, &vao );
//etc
person chakmeshma    schedule 31.05.2013