• Advertisement

Archived

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

Usings externally defined varaibles in C++.

This topic is 6450 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
Advertisement
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)
    
//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?!

Share this post


Link to post
Share on other sites
    
//---------------------------------------------------------------

// The header file

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

#ifndef __MYFILE_H__
#define __MYFILE_H__
//---------------------------------------------------------------#ifdef __cplusplus
extern "C" {

#endif
//---------------------------------------------------------------extern int i;

//---------------------------------------------------------------#ifdef __cplusplus
}

#endif
//---------------------------------------------------------------#endif //__MYFILE_H__

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





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

// The .c or .cpp file

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

#include "myfile.h"
//---------------------------------------------------------------int i;

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


Share this post


Link to post
Share on other sites

  • Advertisement