Click here to Skip to main content
15,792,423 members
Please Sign up or sign in to vote.
2.67/5 (3 votes)
See more:
I was wondering if it was possible to keep my main cpp file in a program free of all the:
int bla, bla2, bla3=1;
bool bla4=false, bla5=false;
double bla 6;
string name;
char bla7;
by putting it all in a header file. Is that possible, and if so, if the main needed to change the value of a variable, would it be able to, and how would the main and the header file end up looking? These are not private variables by the way, they are variables that would be used by main(). Or, do they have to be declared in main()?

You could do that but why? Header files are used to contain common definitions that are used by more than one compilation unit (source file). Items used only within a single unit should be defined in that unit, generally local to each function.
Share this answer
if you declare a variable in a header file then it would be hard for you to include that header file in other file. the problem is compiler would try to create that variable.

What you can do is create a file with the variables and in the header file declare those variable with extern key word
as example:
//variable file:
int a, b, c;
extern int a, b, c;

if you define a variable with extern key word compiler wont create object but will look for that object in other libs

int a, b, c;

extern int a, b, c;

#include "so_called-header_file.h"
Share this answer
jayburn00 6-Jul-12 21:20pm    
just to make sure I understood correctly, variable file is the .cpp file and includefile.h is the headerfile? That kind of defeats the purpose because it seems to be that your just duplicating the code from the main in the includefile without actually making the variable get declared elsewhere, or just making it so the header file declares it as well as the main cpp file. I think I misunderstood your answer or the example, please clarify.
Mohibur Rashid 6-Jul-12 22:27pm    
look up my updated answer.

and this answer does not mean that you would have to do it like exactly this. and go on google and find and read about extern
jayburn00 6-Jul-12 22:56pm    
ok, I see I think. Still looks like its more trouble than its worth. Thanks though

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900