question to Livecoma (or anyone) - linking

Started by
4 comments, last by dadio 22 years, 11 months ago
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? ....
Advertisement
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
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.
[email=JValentine_13@hotmail.com]contact[/email]
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.



Thx A 1000000 !!!! to All !

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

This topic is closed to new replies.

Advertisement