Jump to content
Tuts 4 You

project wide variables in VS2008


Recommended Posts

hi guys,

Here`s a little question that has been bugging me for quiet some time...: How can i declare a project wide variable?

Say, main.cpp holds the function int main(){...}.

In a second file, second.cpp, i have a second function: void second(){...}.

How can these two functions share a string/int/long/... variable?


deep :)

p.s. to makes this clear, this is in no way related to windows environment variables (%tmp%, %%appdata%,...). That`s mostly what i got when using google... :S

Edited by deepzero
Link to comment

I wanted to use a common header file which contained declarations of variables but including it in multiple .cpp files yielded duplicate declaration errors, is there a '#pragma' or 'IFDEF' which makes it so that the variables are declared only the once but the function prototypes and defines can still be used from the same file?



Link to comment

you could try

/* function prototypes */

#ifndef MYHEADER

#define MYHEADER

/* variables */


Funny, none of my books ever mentioned it.

Probably because you don't need "extern" if you use the OO features of C++. With classes you don't have such problems...

Link to comment

Thanks k11. I've tried that before so i must have done something else wrong which caused the compile errors, it seems that MSVC was compiling each .cpp file as a separate module and each module contained these symbols hence the duplicate errors.



Edited by ghandi
Link to comment

Ghandi's method of using the extern is good for related project scope variables.

You can also setup a class in a *.h file

and use:

#pragma once

#include "myclass.h" in every *.h file in your project

remembering to use the #pragma directive where you reference more than once.

Then use something like the example below from your class where you need it:

CmyclassData *pData = new CmyclassData(myclassInfo, myclassmoreinfo);


Edited by CondZero
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Create New...