473,796 Members | 2,839 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

non-static global variables and the extern qualifier

A
Hi,

Consider this code:

//Header File - Foo.h

int i = 0; // non-static global variable

class Foo{
...
};
The scope of i is throughout the entire program since it is global and
non-static. Lets say i want to assign a new value to i in another file
called Bar.h, how is it done?

//Header File - Bar.h

i = 1 //like this? or must i use the extern qualifier here? confusion here
is that it i is global then we u need extern to make it external to another
file when it should be already available?

class Bar{
...
};
Regards,
A
Jul 22 '05 #1
5 3223
A wrote:
Hi,

Consider this code:

//Header File - Foo.h

int i = 0; // non-static global variable

class Foo{
...
};
The scope of i is throughout the entire program since it is global and
non-static.
Right, but you defined i in a header, and if you #include that header in
more than one translation unit, you'll get a linker error for multiple
definitions. Rather define it in the .cpp file, and just declare it in
the header.
Lets say i want to assign a new value to i in another file
called Bar.h, how is it done?

//Header File - Bar.h

i = 1 //like this?
Well, not in the global scope, but within a function, yes.
or must i use the extern qualifier here?
No, but you must have declared it extern.
confusion
here is that it i is global then we u need extern to make it external
to another file when it should be already available?


You should do it something like this:

Foo.cpp:

int i = 0;
//...

Foo.h:

extern int i;

Bar.cpp:

#include "Foo.h"

void somefunc()
{
i = 1;
}

i is defined in Foo.cpp and is global, but other .cpp files like Bar.cpp
don't know anything about it. Just like you have to make a type or a
function from another tranlation unit known, you have to make a
variable known. The "extern int i" tells the compiler that there is a
global variable i of type int that defined elsewhere.

Jul 22 '05 #2
A

A wrote:
Hi,

Consider this code:

//Header File - Foo.h

int i = 0; // non-static global variable

class Foo{
...
};
The scope of i is throughout the entire program since it is global and
non-static.


Right, but you defined i in a header, and if you #include that header in
more than one translation unit, you'll get a linker error for multiple
definitions. Rather define it in the .cpp file, and just declare it in
the header.


Firstly, i agree with the error.

#include would obviously bring i into scope wherever you included it, and
thus defeats the purpose of the external qualifier? I gather from what Ive
read that by using the external qualifer you can open the scope to multiple
files - it does not make mention of also using #include.

I was thinking more on the lines:

Foo.h

int i = 0; // non-static global variable

class Foo{
...
};

Bar.h

extern int i; //refers to the i declared in Foo.h; no need to use #include

class Bar{
...
};
Regards,
A
Jul 22 '05 #3
A wrote:

A wrote:
> Hi,
>
> Consider this code:
>
> //Header File - Foo.h
>
> int i = 0; // non-static global variable
>
> class Foo{
> ...
> };
>
>
> The scope of i is throughout the entire program since it is global
> and non-static.
Right, but you defined i in a header, and if you #include that header
in more than one translation unit, you'll get a linker error for
multiple definitions. Rather define it in the .cpp file, and just
declare it in the header.


Firstly, i agree with the error.

#include would obviously bring i into scope wherever you included it,
and thus defeats the purpose of the external qualifier?


Why?
If you write:

int i = 0;

it lets the compiler know there is an int named i _and_ that it should
allocate space for that int.

extern int i;

also lets the compiler know there is an int named i, but it does _not_
allocate storage for it. So the extern just means "there is a variable,
but it alredy exists somewhere else". The linker will resolve it then.
I gather from what Ive read that by using the external qualifer you
can open the scope to multiple files - it does not make mention of
also using #include.
I was thinking more on the lines:

Foo.h

int i = 0; // non-static global variable

class Foo{
...
};


Well, this would only be ok as long as you #include "Foo.h" only _once_
in your whole program. But that would defeat the purpose of headers.
Bar.h

extern int i; //refers to the i declared in Foo.h; no need to use
#include
Right. But headers are just there to make things from one translation
unit known to another one. You put it all in a header so that you don't
need to repeat everything wherever it is needed. And just as you would
put a function declaration in the header and define it in the .cpp
file, you should only declare your global variables (and that's what
the extern actually means) in the header and put the definition in
the .cpp file.
class Bar{
...
};


Jul 22 '05 #4
On Wed, 26 Nov 2003 21:32:53 +1030, "A" <A@iprimus.com. au> wrote in
comp.lang.c++:
Hi,

Consider this code:

//Header File - Foo.h

int i = 0; // non-static global variable
Actually, i is defined without the static keyword, but it is indeed a
static object, meaning that is has static storage duration.
class Foo{
...
};
The scope of i is throughout the entire program since it is global and
No, you are confusing scope with linkage. The definition of i has
namespace scope in C++, and since it is at top level in the global
namespace, it is basically the same as what is called "file scope" in
C, even though that terminology is no longer used in C++.

The definition is in scope from the point where it appears in the
translation unit until the end of the translation unit, although it
may be hidden by another usage of the same name in an inner block.
non-static. Lets say i want to assign a new value to i in another file
called Bar.h, how is it done?
You can only assign a value to an object in code. You can only
initialize an object in its definition. So if i is defined in a
source file, you can't initialize it anywhere else, and you must
assign to it from inside a function, not at file level.
//Header File - Bar.h

i = 1 //like this? or must i use the extern qualifier here? confusion here
is that it i is global then we u need extern to make it external to another
file when it should be already available?

class Bar{
...
};
Regards,
A


You have some confusion over three separate but somewhat related
concepts, scope, linkage, and storage duration. Part of the confusion
stems from the fact that C++ inherited two different meanings of the
"static" keyword from C, not to mention adding another meaning of its
own.

Any object defined outside of a function has static storage duration,
which means it exists for the life of your program. Adding the
keyword "static" or the keyword "const" to such an object does not
change the storage duration, which is still static, and does not
change the scope, which is still to the end of the translation unit,
it merely changes the linkage from internal to external.

External linkage means that code in another translation unit may refer
to the object by name, provided that that code has a suitable external
declaration in its scope.

And the definition of translation unit is basically the source file
you pass to the compiler plus everything it includes.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Jul 22 '05 #5
"Jack Klein" <ja*******@spam cop.net> wrote...
[...]
Any object defined outside of a function has static storage duration,
which means it exists for the life of your program. Adding the
keyword "static" or the keyword "const" to such an object does not
change the storage duration, which is still static, and does not
change the scope, which is still to the end of the translation unit,
it merely changes the linkage from internal to external.


Vice versa, actually. "static" changes linkage from external to internal.

Victor
Jul 22 '05 #6

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

Similar topics

12
4433
by: lothar | last post by:
re: 4.2.1 Regular Expression Syntax http://docs.python.org/lib/re-syntax.html *?, +?, ?? Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. the regular expression module fails to perform non-greedy matches as described in the documentation: more than "as few characters as possible"
5
3756
by: klaus triendl | last post by:
hi, recently i discovered a memory leak in our code; after some investigation i could reduce it to the following problem: return objects of functions are handled as temporary objects, hence their dtor is called immediately and not at the end of the function. to be able to use return objects (to avoid copying) i often assign them to a const reference. now, casting a const return object from a function to a non-const reference to this...
3
12271
by: Mario | last post by:
Hello, I couldn't find a solution to the following problem (tried google and dejanews), maybe I'm using the wrong keywords? Is there a way to open a file (a linux fifo pipe actually) in nonblocking mode in c++? I did something ugly like --- c/c++ mixture --- mkfifo( "testpipe", 777);
25
7652
by: Yves Glodt | last post by:
Hello, if I do this: for row in sqlsth: ________pkcolumns.append(row.strip()) ________etc without a prior:
32
4528
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
11
3456
by: ypjofficial | last post by:
Hello All, So far I have been reading that in case of a polymorphic class ( having at least one virtual function in it), the virtual function call get resolved at run time and during that the vtable pointer is made use of.. eg. class one {
2
6122
by: Ian825 | last post by:
I need help writing a function for a program that is based upon the various operations of a matrix and I keep getting a "non-aggregate type" error. My guess is that I need to dereference my pointers, but I'm not sure. Please help. The code: void equate(matrix *A, matrix *B) { int i, j; assert(A.row_dim == B.col_dim && A.col_dim == B.col_dim); for(i=0; i < A.row_dim; i++) for(j=0; j < A.col_dim; j++)
0
2346
by: amitvps | last post by:
Secure Socket Layer is very important and useful for any web application but it brings some problems too with itself. Handling navigation between secure and non-secure pages is one of the cumbersome jobs. When a non-secure page references a secure page with relative URL, the web server generates error until absolute URL with https prefix is used. On the other hand when a secure page references a non-secure page, the non-secure page will be...
399
12954
by: =?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= | last post by:
PEP 1 specifies that PEP authors need to collect feedback from the community. As the author of PEP 3131, I'd like to encourage comments to the PEP included below, either here (comp.lang.python), or to python-3000@python.org In summary, this PEP proposes to allow non-ASCII letters as identifiers in Python. If the PEP is accepted, the following identifiers would also become valid as class, function, or variable names: Löffelstiel,...
12
29919
by: puzzlecracker | last post by:
is it even possible or/and there is a better alternative to accept input in a nonblocking manner?
0
10221
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10169
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10003
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
9050
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
7546
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
6785
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
5440
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
5569
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.