Archived

This topic is now archived and is closed to further replies.

dadio

question to Livecoma (or anyone) - linking

Recommended Posts

Hi, I tried to put some external global variables in a .h file, and included it in the 2 .cpp files I have, but I get a linking error: rendering.obj : error LNK2005: "char * className" (?className@@3PADA) already defined in main.obj does anyone have an idea? ....

Share this post


Link to post
Share on other sites
Ok your problem is that the variable in the header file is getting defined as a variable in both of the C++ files, one way to avoid this would be to use some #define''s like this

... in header file
#ifndef _MAIN_C
#define DECLARE
#else
#define DECLARE extern
#endif

DECLARE int myvar;

... in main .cpp file
#define _MAIN_C
#include

this will make it so that the variable is only defined inside the main cpp file, and the other cpp file will see that variable as an external variable, but will still have access to it

Share this post


Link to post
Share on other sites
Another way is to make sure that each .h file is only processed once. just put this at the beginning of each .h file
#ifndef FILENAME_H
#define FILENAME_H

... everything here

and this at the end
#endif

the compiler will only see one instance of each declaration in the .h file


Feel free to email me.

Share this post


Link to post
Share on other sites
Heres how I set up my header file when I changed the structure of the tutorial 1 code minus the comments....

//////////////////////////////////////////////////////


#if !defined PREVENT_DUPLICATE_CODE
#define PREVENT_DUPLICATE_CODE

#define WIN32_LEAN_AND_MEAN

#include
#include

#include

extern bool keys[256];
extern bool active;
extern bool fullscreen;
extern HGLRC hRC;
extern HDC hDC;
extern HWND hWnd;
extern HINSTANCE hInstance;

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow);

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

GLvoid ReSizeGLScene(GLsizei width, GLsizei height);

GLvoid KillGLWindow(GLvoid);

int InitGL(GLvoid);

int DrawGLScene(GLvoid);

BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag);

////////////////////////////////////////////////////////////

I defined all my gloabals in a seprate .cpp file. Everything is working good now.



Share this post


Link to post
Share on other sites
Well, I forgot about that other method when I wrote my post. You should probably use it rather than what I said, because it is more general, and easier to use. It''s been too long since I''ve used global variables shared across multiple files

Share this post


Link to post
Share on other sites