Usings externally defined varaibles in C++.
I have a header file which defines a variable
I need to access in my main part of my code.
I keep getting VC++ error saying the the variable
is already defined in the main part of the code
(in game.obj) even though it is not.
In the header file the (start.h) the variable is
defined as follows...
extern int player_count;
What is the proper way to access this variable in game.cpp?
Well, assuming I understand you correctly, here is what I would do... (Assuming you want to define the variable in the header file)
(Assume header file''s name is MyFile or something)
Hope that helps you out?!
(Assume header file''s name is MyFile or something)
//First, make sure that you secure against it being included //multiple times:#ifndef MYFILE_H#define MYFILE_H//Here is the variable you want defined...int MyVariable;#endif//Then, in your Game.cpp file (and anywhere else you want access// to that variable...//First make sure you include the header file#include "MyFile.h"//Then, this is how you tell the compiler that you want to //access a variable defined in another file:extern int MyVariable;
Hope that helps you out?!
//---------------------------------------------------------------// The header file//---------------------------------------------------------------#ifndef __MYFILE_H__#define __MYFILE_H__//---------------------------------------------------------------#ifdef __cplusplusextern "C" {#endif//---------------------------------------------------------------extern int i;//---------------------------------------------------------------#ifdef __cplusplus}#endif//---------------------------------------------------------------#endif //__MYFILE_H__//---------------------------------------------------------------//---------------------------------------------------------------// The .c or .cpp file//---------------------------------------------------------------#include "myfile.h"//---------------------------------------------------------------int i;//---------------------------------------------------------------
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement