473,811 Members | 3,686 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

accessing variables from more than one .cpp file

hi, sorry if this has been adressed some where elss. if it has plz can you
point me to it and ill go read it.

any way, i want to declare some variables with in a header file. lets say
int i;

i then want to be able to acess that variable from multipul .cpp files where
I can read it and also change the value. i would like to hold it in a
struct or a class eventualy but i can't even get it to work on its own at
min, so i thought id start off simple and ask how i do it just like what i
described above.

any help would be grate,

thx scott
Jul 22 '05 #1
8 1976

"scott" <sc***********@ hotmail.com> wrote in message
news:ck******** **@news5.svr.po l.co.uk...
hi, sorry if this has been adressed some where elss. if it has plz can you
point me to it and ill go read it.

any way, i want to declare some variables with in a header file. lets say
int i;

i then want to be able to acess that variable from multipul .cpp files
where
I can read it and also change the value. i would like to hold it in a
struct or a class eventualy but i can't even get it to work on its own at
min, so i thought id start off simple and ask how i do it just like what i
described above.

any help would be grate,

thx scott


Put this in the header file

extern int i;

Put this in *one* .cpp file

int i;

Include the header file in every .cpp file where you need to use it.

What goes in the header file is called a declaration, what goes in the one
..cpp file is called a definition. You can have as many declarations as you
like but you must have only have one definition. This is the One Definition
Rule. Understanding the difference between declarations and definitions is
an important C++ concept to master.

BTW i is a fantastically bad name for a global variable.

john
Jul 22 '05 #2
scott wrote:
hi, sorry if this has been adressed some where elss. if it has plz can you
point me to it and ill go read it.

any way, i want to declare some variables with in a header file. lets say
int i;
If you want to declare it, add 'extern' to it:

extern int i;
i then want to be able to acess that variable from multipul .cpp files where
I can read it and also change the value. i would like to hold it in a
struct or a class eventualy but i can't even get it to work on its own at
min, so i thought id start off simple and ask how i do it just like what i
described above.


Include that header wherever you need that variable. Then in only one
of the files add a definition of that variable:

int i;

(to make it a true definition you could also initialise it to something:

int i = 42;

}

Then compile and link. All should work.

Oh, and find yourself a good book. Things like this gotta be covered in
them. I can't imagine that they wouldn't be.

Victor
Jul 22 '05 #3
an alternative is to declare the variables like this:

#ifndef EXTERN
#define EXTERN extern
#endif

EXTERN int i;

Then include the file wherever you want, but in exactly one place (probably
wherever MAIN or WinMain is)
do this before including it:

#define EXTERN

That will default the declarations to 'extern' linkage but allow you to override
it in the one place the things need to be made globals.

David

scott wrote:
hi, sorry if this has been adressed some where elss. if it has plz can you
point me to it and ill go read it.

any way, i want to declare some variables with in a header file. lets say
int i;

i then want to be able to acess that variable from multipul .cpp files where
I can read it and also change the value. i would like to hold it in a
struct or a class eventualy but i can't even get it to work on its own at
min, so i thought id start off simple and ask how i do it just like what i
described above.

any help would be grate,

thx scott

Jul 22 '05 #4
scott posted:
hi, sorry if this has been adressed some where elss. if it has plz can
you point me to it and ill go read it.

any way, i want to declare some variables with in a header file. lets
say int i;

i then want to be able to acess that variable from multipul .cpp files
where I can read it and also change the value. i would like to hold it
in a struct or a class eventualy but i can't even get it to work on its
own at min, so i thought id start off simple and ask how i do it just
like what i described above.

any help would be grate,

thx scott

A C++ program is a collection of ".cpp" files and nothing more.

When you compile a C++ program, you supply the compiler with the ".cpp"
files, for example:

g++ monkey.cpp cow.cpp orange.cpp

The compiler will create an executable for you.

The "monkey.cpp " can use functions and global variables defined in the two
other files, "cow.cpp" and "orange.cpp ", and vice versa.
So let's say in "cow.cpp", you have a global variable as so:

//cow.cpp

int cow = 7;
Now, while "monkey.cpp " is being compiled, the compiler comes across:

//monkey.cpp

int main()
{
cow += 6;
}
But... the problem here is that "monkey.cpp " hasn't got a clue about the
variable "cow". To remedy the situation, if you were to do:

//monkey.cpp

int cow;

int main()
{
cow += 6;
}
Then there would be no problem at all with "monkey.cpp ", but then when the
compiler goes to compile the three files together it will say:

ERROR: Multiple Definitions

So... what you want is a declaration, which says: "Don't actually create
(define) a variable, all I want to do is let you know about one that already
exists". You do this as follows:

//monkey.cpp

extern int cow;

int main()
{
cow +=4;
}
//cow.cpp

int cow;
Now when you compile "monkey.cpp " and "cow.cpp" together, everything will be
perfect.

But...

if you compile "monkey.cpp " on its own, there will be an error - you access
the variable "cow", so there must be a definition of it.

So... in summation...

If you want to have a global variable and give other .cpp files access to it
via a header file, this is how it's done:
//blah.hpp

extern int blah;
//blah.cpp

int blah = 5;

Then all the other .cpp files have to do is include "blah.hpp". And one more
thing... when they're compiling their program, they've to put in "blah.cpp"
with it aswell, for example:

g++ myfile.cpp blah.cpp
One more thing:
When you put the following in a ".cpp" file:

#include "blah.hpp"
What happens is that the exact contents of the header file get copy-and-
pasted into where the #include line was.
And one more little thing: Google for "inclusion guards".
-JKop
Jul 22 '05 #5
In article <41************ ***@bluegrass.n et>, David Lindauer top-posted:
an alternative is to declare the variables like this:

#ifndef EXTERN
#define EXTERN extern
#endif

EXTERN int i;

Then include the file wherever you want, but in exactly one place
(probably wherever MAIN or WinMain is) do this before including it:

#define EXTERN

That will default the declarations to 'extern' linkage but allow you
to override it in the one place the things need to be made globals.

David


This seems really clumsy to me. You've replaced the need to define the
variable in exaclty one translation unit with the need to define a
preprocessor symbol in exactly one translation unit. Putting the two
approaches side-by-side shows this:

-------------------
Your solution

// file foo.h
#ifndef EXTERN
#define EXTERN extern
#endif
EXTERN int i;

// file foo_user1.cpp
#include "foo.h"

// file foo_user2.cpp
#define EXTERN
#include "foo.h"

-------------------
Typical solution

// file foo.h
extern int i;

// file foo_user1.cpp
#include "foo.h"

// file foo_user2.cpp
#include "foo.h"
int i = 0;
So it's the same conceptually, yet less clear to other people and more
lines of code, and also probably doesn't scale well to the purpose
of defining multiple globals in different translaction units.

Jul 22 '05 #6


scott urban wrote:
In article <41************ ***@bluegrass.n et>, David Lindauer top-posted:
an alternative is to declare the variables like this:

#ifndef EXTERN
#define EXTERN extern
#endif

EXTERN int i;

Then include the file wherever you want, but in exactly one place
(probably wherever MAIN or WinMain is) do this before including it:

#define EXTERN

That will default the declarations to 'extern' linkage but allow you
to override it in the one place the things need to be made globals.

David


This seems really clumsy to me. You've replaced the need to define the
variable in exaclty one translation unit with the need to define a
preprocessor symbol in exactly one translation unit. Putting the two
approaches side-by-side shows this:


I use that approach in some projects, because where I work it is common to
have a single global header file that defines *everything*. Rather than
maintain two versions of each variable declaration (which both have to be
created and then modified if there are changes) I do this. I agree if you
are scattering your globals
all over in different files this approach isn't very clear, however. But
for the case where you have a single global file it actually works out a
little better... and in reality it doesn't matter *where* you define things
as long as they get defined.

David
Jul 22 '05 #7
> and in reality it doesn't matter *where* you define things
as long as they get defined.


Oh yes it does! See the FAQ
http://www.parashift.com/c++-faq-lit...html#faq-10.11

john
Jul 22 '05 #8


John Harrison wrote:
and in reality it doesn't matter *where* you define things
as long as they get defined.


Oh yes it does! See the FAQ
http://www.parashift.com/c++-faq-lit...html#faq-10.11

john


oops sorry I was in "C" mode. I forgot about the problems in C++...

David
Jul 22 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1780
by: Earl Teigrob | last post by:
I am programming ASP.NET using C#. I have been accessing static variables accross my entire application but now need to change some of the static variables that are session specific to instance variables. (For more background, see previous post about 30 min ago) It was so cool using static variables because they where global to the entire application so I could calculate them when the page loaded and use then anywhere in the app. Now...
2
5217
by: Nathan Sokalski | last post by:
I would like to access variables and functions that I declare in the Global.asax.vb file. However, I am having trouble doing that. What does the declaration have to look like in the Global.asax.vb file, and what would I do to access it? (I am using VB.NET for my code) Thanks. -- Nathan Sokalski njsokalski@hotmail.com http://www.nathansokalski.com/
9
5408
by: Bob Day | last post by:
VS 2003, vb.net , sql msde... I have an application with multiple threads running. Its a telephony application where each thread represents a telephone line. For code that would be the same for each thread, I put in Shared methods as below. It is only now that I am realizing the complexity of multiple threads accessing shared methods. And, quite honestly, I am very confused. I have tried System.Threading.Monitor.Enter, Synclock,...
8
2747
by: dwok | last post by:
I have been wondering this for a while now. Suppose I have a class that contains some private member variables. How should I access the variables throughout the class? Should I use properties that expose the variables or is it OK to just access the variables directly? Keep in mind that I am talking about accessing the variables from within the class that they are defined. Thanks!
0
12090
by: sonu | last post by:
I have following client side code which i have used in my asp.net project SummaryFeatured Resources from the IBM Business Values Solution Center WHITEPAPER : CRM Done Right Improve the likelihood of CRM success from less than 20 percent to 60 percent. WHITEPAPER :
5
2478
by: TS | last post by:
is it preferred to access member variables directly in code, on the page that declared them, versus going thru a property accessor? I would think that since theres no security concerns or anything it would be more efficient to access directly. I also don't think that you would need to do any special validation since the class developer knows what the rules are. Note, i am not referring to accessing member variables declared in a...
12
11725
by: Steve Blinkhorn | last post by:
Does anyone know of a way of accessing and modifying variables declared static within a function from outside that function? Please no homilies on why it's bad practice: the context is very particular and involves automatically generated code. I know several other ways of attacking my problem, but this would be the cleanest if it could be made to work. A little more context. I use C as the output of a code generating system which...
1
1720
by: Greg Scharlemann | last post by:
There is probably an easy solution to this that I've overlooked somewhere... I have a main file, call it main.php, and an include file, myInclude.php. I'm accessing main.php via: http://www.example.com/main.php?page=new&var1=test&var2=test2 main.php: ------------------- <?php
2
2358
by: Jurek Dabrowski | last post by:
hi all, I have a question in reference to accessing variables in another class maybe someone has dealt with before. I have some public variables declared in my main plug-in class CCommandMeshToSrf, eg: BOOL m_bHaveAnswer; I want to set this variable from within a dialog class which is defined in separate .h and .cpp files of course. How would one access this varibale from a method defined in my CTestModelessDialog class ?
0
9726
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10647
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10130
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9204
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7667
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6887
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5553
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5692
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3865
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.