Jump to content
Tuts 4 You

project wide variables in VS2008


deepzero

Recommended Posts

Posted (edited)

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?

thanx,

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
Posted

main.cpp: int test;

second.cpp: extern int test;

Posted

that seems to be it.

Funny, none of my books ever mentioned it.

thanks a lot, k11! :)

Posted

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?

HR,

Ghandi

Posted

you could try

/* function prototypes */

#ifndef MYHEADER

#define MYHEADER

/* variables */

#endif

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...

Posted (edited)

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.

HR,

Ghandi

Edited by ghandi
Posted (edited)

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);

CZ

Edited by CondZero

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...