Posted November 27, 201014 yr 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, 201014 yr by deepzero
November 27, 201014 yr Author that seems to be it. Funny, none of my books ever mentioned it. thanks a lot, k11!
November 27, 201014 yr 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
November 27, 201014 yr 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...
November 27, 201014 yr 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, 201014 yr by ghandi
November 29, 201014 yr 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, 201014 yr by CondZero
Create an account or sign in to comment