PDA

View Full Version : how to share variables



sksingh73
1st July 2010, 13:12
in my program, i have 2 cpp & their 2 header files. i want to access variable from one cpp file to other. There is no problem when i access int variable, but when i try to access quint32 variable, its value is not the same which is there in original cpp file. my code is

//hash.h
public:
hashchain(QWidget *parent = 0);
quint32 initial_key, session_key; //variable originally declared here
int num;

//hash.cpp
void hashchain::display()
{
quint32 unum[10];
int i;
for(i=0;i<10;i++)
unum=0;
ifstream in("session", ios::in|ios::binary);
in.read((char *)&unum, sizeof(unum));
initial_key = unum[9];
session_key = unum[8]; //value session_key defined here

//comn.h
#include "hash.h"

private:
hashchain *hashch;
quint32 sessionkey;
int val;

//comn.cpp quint32 session_key being accessed from this file
void comn::display_mac()
{
hashch = new hashchain(this);
sessionkey = hashch->session_key; //declaration here
val = hashch->num;
qDebug() << "Session key: " << sessionkey; //value being displayed here is not same as in hash.cpp, above
qDebug() << "num: " << val;

}

high_flyer
1st July 2010, 14:17
No disrepect, but:
This is a Qt related forum, not basic C programming forum, and your question is basic C programming question, and thus off topic.
You will probably be better off posting such questions on beginners C programming forums.
The forum "Newbie" here is meant as newbie to Qt, not to C/C++.

sirius
1st July 2010, 23:59
I agree with high_flyer, but I think he should have given you a hint in the right direction. Go get a good book on C++ and read about extern storage class specifier :)

sksingh73
2nd July 2010, 04:46
Thanx for your advice, but i don't think with extern you can share variable between 2 cpp files with their separate header file. If i am not wrong, extern can be used between 2 cpp files with a common header file.

tbscope
2nd July 2010, 04:54
As already mentioned, this is basic C++. There are some good free books online that will explain object oriented programming. You just need to take a little bit of time and read some chapters about it. It's boring, I know, but it's necessary.

Sharing data between classes is actually very easy.



Class1
{
public:
Class1{}
~Class1{}

void doSomething();
int getValue() const;

private:
int m_value;
};

Class1::Class1()
{
m_value = 1;
}

void Class1::doSomething()
{
m_value = 2;
}

int Class1::getValue() const
{
return m_value;
}

Then from anywhere else in the code, you can do:


Class1 *myClass1 = new Class1;
myClass1->doSomething();
int theValue = myClass1->getValue();
delete myClass1;