deepzero Posted November 27, 2010 Posted November 27, 2010 (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 November 27, 2010 by deepzero
Aguila Posted November 27, 2010 Posted November 27, 2010 main.cpp: int test;second.cpp: extern int test;
deepzero Posted November 27, 2010 Author Posted November 27, 2010 that seems to be it. Funny, none of my books ever mentioned it. thanks a lot, k11!
ghandi Posted November 27, 2010 Posted November 27, 2010 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
Aguila Posted November 27, 2010 Posted November 27, 2010 you could try/* function prototypes */#ifndef MYHEADER#define MYHEADER/* variables */#endifFunny, 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...
ghandi Posted November 27, 2010 Posted November 27, 2010 (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 November 27, 2010 by ghandi
CondZero Posted November 29, 2010 Posted November 29, 2010 (edited) Ghandi's method of using the extern is good for related project scope variables.You can also setup a class in a *.h fileand use:#pragma once#include "myclass.h" in every *.h file in your projectremembering 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 November 29, 2010 by CondZero
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now