2015-01-11 3 views
2

У меня есть то, что кажется общим вопросом, но я не могу решить его в контексте моего кода. Недавно я начал класс, в котором меня бросили в C++ и OpenGL без предварительного знания C++, поэтому, пожалуйста, будьте спокойны. Вот мои 3 файла, предназначенные для открытия окна OpenGL; Однако я поздоровался с хорошей ошибкой LNK2005:LNK2005 (уже определено) не найден Ошибка

error LNK2005: "public: static unsigned int JWindow::id" ([email protected]@@2IA) already defined in Application.obj X:\School\comp2501\COMP2501Tutorial1\COMP2501Tutorial1\Main.obj ‌​COMP2501Tutorial1

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

main.cpp

#include <windows.h>  // Standard header for MS JWindows applications 
#include <freeglut.h> 
#include "Application.h" 

#define KEY_ESCAPE 27 

static GLfloat lightPos[] = { 1.0, 1.0, 1.0, 0.0 }; 

void drawCube(GLdouble x0, GLdouble x1, GLdouble y0, GLdouble y1, GLdouble z0, GLdouble z1) {/**/} 

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

    JWindow::create(640, 480, "Tutorial 1", 45.0f, 0.1f, 500.0f); 

    // initialize and run program 
    glutInit(&argc, argv);          // GLUT initialization 
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); // Display Mode (RGBA color|two screen buffers| use depth buffer) 

    glutInitWindowSize(JWindow::width, JWindow::height);    // set JWindow size 

    glutDisplayFunc(JWindow::display);         // register display function 
    glutIdleFunc(JWindow::display);          // register idle function 
    glutKeyboardFunc(JWindow::keyboard);         // register keyboard function 
    glutCloseFunc(JWindow::close);          // register close function 


    JWindow::initialize();            // intialization 
    glutMainLoop();            // run GLUT mainloop 
} 

Application.h

class JWindow{ 
public: 
    static void updateProjection(); 
    static void render(); 
    static void initialize(); 
    static void timer(int); 
    static void display(); 
    static void close(); 
    static void create(int, int, char*, float, float, float); 
    static void keyboard(unsigned char, int, int); 

    static GLuint id; 
    static char* title; 

    static int width; 
    static int height; 

    static float fovAngle; 

    static float zNear; 
    static float zFar; 

}; 


GLuint JWindow::id = 0; 
char* JWindow::title = "JWindow"; 
int JWindow::width = 0; 
int JWindow::height = 0; 
float JWindow::fovAngle = 0.0f; 
float JWindow::zNear = 0.0f; 
float JWindow::zFar = 0.0f; 

Application.cpp

#include <freeglut.h> 
#include "Application.h" 

#define KEY_ESCAPE 27 

void JWindow::updateProjection() 
{ 
    glutSetWindow(JWindow::id);              // tell opengl which JWindow you want to change 
    JWindow::height = (JWindow::height < 1) ? 1 : JWindow::height;       // make sure we are not dividing by zero for the aspect 
    glViewport(0, 0, JWindow::width, JWindow::height);         // set the viewport 

    glMatrixMode(GL_PROJECTION);            // select projection matrix 
    glLoadIdentity();               // reset projection matrix 

    GLfloat aspect = (GLfloat)JWindow::width/JWindow::height;       // calculate aspect ratio 
    gluPerspective(JWindow::fovAngle, aspect, JWindow::zNear, JWindow::zFar);  // set up a perspective projection matrix 
} 


// Render data to the screen 
void JWindow::render() 
{ 
glClearColor(0.25f, 0.25f, 0.25f, 1.0f); 
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);   // Clear Screen and Depth Buffer 
glMatrixMode(GL_MODELVIEW);         // Tell opengl we are working with the modelview matrix 
glLoadIdentity();           // Set the modelview matrix to the identity matrix 

gluLookAt(0.0f, 0.0f, 10.0f, //position 
    0.0f, 0.0f, 0.0f,  //look at position 
    0.0f, 1.0f, 0.0f); //up vector 
/* 
glBegin(GL_TRIANGLES);    // Send the following information as triangles 
glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // glColor4f(red,green,blue,alpha) 
glVertex3f(-1.0f, -1.0f, 0.0f);  // glVertex3f(x,y,z) 

glColor4f(0.0f, 1.0f, 0.0f, 1.0f); 
glVertex3f(1.0f, -1.0f, 0.0f); 

glColor4f(0.0f, 0.0f, 1.0f, 1.0f); 
glVertex3f(-1.0f, 1.0f, 0.0f); 

glEnd();       // tell opengl we are done sending data 
*/ 
    //drawCube(-1, 1, -1, 1, -1, 1); 
    glutSolidTorus(1, 2, 10, 10); 
    glutSwapBuffers(); //works with GL_DOUBLE. use glFlush(); instead, if using GL_SINGLE 
} 

// Function called when timer ends 
void JWindow::timer(int id) { 
    glutPostRedisplay();   // Tell GLUT to call it's glutDisplayFunc 
} 

// Set new timer and render 
void JWindow::display(void) 
{ 
    glutTimerFunc(17, timer, 1); //Call timer function in at least 17 milliseconds 
    glutSetWindow(JWindow::id);  //Tell glut which JWindow we are working on (only needed for multiple JWindows) 
JWindow::render();   //Call our render function 
} 

//get keyboard input 
void JWindow::keyboard(unsigned char key, int mousePositionX, int mousePositionY) 
{ 
    switch (key) 
    { 
    case KEY_ESCAPE: 
     glutExit(); //if ESC key is pressed, quit 
     break; 

    default: 
     break; 
    } 
} 

// callback function when glut ends 
void JWindow::close() 
{ 
    //memory cleanup when program quits 
} 

void JWindow::initialize() 
{ 
    glEnable(GL_DEPTH_TEST); 
    glEnable(GL_CULL_FACE); 
    glCullFace(GL_BACK); 
    glClearColor(0.0, 0.0, 0.0, 1.0); 

    glEnable(GL_LIGHTING); 
    glEnable(GL_LIGHT0); 

    glViewport(0, 0, JWindow::width, JWindow::height);      // set the viewport 

    glMatrixMode(GL_PROJECTION);         // select projection matrix 
    glLoadIdentity();            // reset projection matrix 
    GLfloat aspect = (GLfloat)JWindow::width/JWindow::height;    // calculate aspect ratio 
    gluPerspective(JWindow::fovAngle, aspect, JWindow::zNear, JWindow::zFar); // set up a perspective projection matrix 

} 

void reshape(GLint newWidth, GLint newHeight) { 

} 

void JWindow::create(int w, int h, char* t, float fov, float n, float f){ 
    JWindow::width = w; 
    JWindow::height = h; 
    JWindow::title = t; 
    JWindow::fovAngle = fov; 
    JWindow::zNear = n; 
    JWindow::zFar = f; 
    JWindow::id = glutCreateWindow(JWindow::title); 
} 
+0

Не могли бы вы дать полный текст ошибки? Кроме того, класс полностью статических членов обычно является запахом кода. –

+0

Да, я знаю, что класс всех статических членов, как правило, плохой, но у меня есть планы по добавлению других участников, однако это единственные в настоящее время. Для каждого члена JWindow я получаю сообщение об ошибке: Ошибка \t \t 1 ошибка LNK2005: (? ID @ JWindow @@ 2IA): "открытые статические неподписанных INT JWindow :: идентификатор" уже определен в Application.obj \t X: \ Школа \ comp2501 \ COMP2501Tutorial1 \ COMP2501Tutorial1 \ Main.obj \t COMP2501Tutorial1 – JStevens

+0

Честно говоря, похоже, что ни один из этих членов (данные и функции) не должен быть статичным! –

ответ

5

Вы должны переместить инициализацию ваших статических членов в файл Application.cpp:

GLuint JWindow::id = 0; 
char* JWindow::title = "JWindow"; 
int JWindow::width = 0; 
int JWindow::height = 0; 
float JWindow::fovAngle = 0.0f; 
float JWindow::zNear = 0.0f; 
float JWindow::zFar = 0.0f; 

Это определения статических элементов. Если вы включите их в несколько единиц перевода (что вы сделали), у вас есть несколько определений.

+0

Работал как шарм! Спасибо – JStevens

+0

@JStevens Нет проблем. Кроме того, не забывайте, что у вас есть охранники. –

Смежные вопросы