#### Archived

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

# Usings externally defined varaibles in C++.

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

## 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 on other sites
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 on other sites
  //---------------------------------------------------------------// 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;//---------------------------------------------------------------

1. 1
2. 2
Rutin
24
3. 3
4. 4
JoeJ
16
5. 5

• 14
• 29
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631773
• Total Posts
3002265
×