473,799 Members | 2,988 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

declare vs define of global variables

According to my programming textbook, "int a;" at the top level of a
file is a definition which shouldn't go in a header file.
However, I'm running into a lot of online documentation that treats that
kind of statement as a declaration that can be in a header file used in
multiple compilation units.
Which of these is correct? Is this something that has changed between
different standards?
Nov 14 '05 #1
7 6144
On Mon, 4 Oct 2004 22:41:52 -0400, Brian Sammon
<us****@brisamm on.fastmail.fm> wrote in comp.lang.c:
According to my programming textbook, "int a;" at the top level of a
file is a definition which shouldn't go in a header file.
However, I'm running into a lot of online documentation that treats that
kind of statement as a declaration that can be in a header file used in
multiple compilation units.
Which of these is correct? Is this something that has changed between
different standards?

What kind of online documentation? What reason do you have to trust
its quality? If this documentation talks about using a declaration
like:

int a;

....without either the 'static' or 'extern' keywords at file scope, the
documentation is just plain wrong, and nothing has changed in
different versions of the C standard in this regard.

At file scope a definition like:

int a; /* no initializer */

....is called a 'tentative definition'. The identifier 'a' is declared
with file scope to have static storage duration, int type, and
external linkage. There may be more than one tentative definition for
the same identifier at file scope, as long as they all apply to the
same object type:

When there is a tentative definition in the file, one of two things
happens.

1. There is a later definition with an initializer (called an
'external definition'):

int a = 42;

2. There is no external definition, that is file scope declaration
with an initializer. In this case, at the end of the translation
unit, the compiler will act as though an external definition with an
initializer of 0 existed.

According to the C standard, you produce undefined behavior and C
takes no responsibility for the results by defining an object with
external linkage in multiple translation units. The standard states
that for each external object that is actually referenced in a
program, there must be exactly one definition.

It just so happens that there are some compiler/linker combinations
that allow this, as long as no more than one source file contains an
initializer for the object. It also happens that there are other
compiler/linker combinations that will reject the program even if none
of the source files contains an initializer.

In any case, it is specifically invalid and non-portable.

--
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++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #2
On Mon, 4 Oct 2004 22:41:52 -0400, Brian Sammon
<us****@brisamm on.fastmail.fm> had a scratch and wrote:
According to my programming textbook, "int a;" at the top level of a
file is a definition which shouldn't go in a header file.
However, I'm running into a lot of online documentation that treats that
kind of statement as a declaration that can be in a header file used in
multiple compilation units.
Which of these is correct? Is this something that has changed between
different standards?

extern int a; /* an allusion to a - it tells the compiler to look
elsewhere for the definition - that's what you'd expect in a header
file *./

int a; /* a tentative definition or an allusion - it's up to the
compiler to decide on the basis of what's elsewhere in the source file
*/

int a=0; /* a real definition */
ANSI, K&R, and Unix all have different strategies for resolving
tentative definitions, allusions, and real declarations.


=============== ======

Pussie sHaveMo
reFunMeow MeowMeowPus
siesHaveMore FunMeowMeowMeo
wPussiesHaveMo reFunMeowMeowMe o
wPussiesHaveMor eFunMeowMeowMeo wP
ussiesHaveMoreF u nMeowMeowMeowPu ssi
esHaveMoreFunMe o wMeowMeowPussie sHav
eMoreFunMeowMeo wM eowPussiesHaveM or
eFunMeowMeowMeo wP ussiesHaveMoreF unM
eowMeowMeowPuss ie sHaveMoreFunMeo wMe owMeowPus
siesHaveM oreFunMeowMeowM e owPussiesHaveMo re FunMeowMeowMe
owPussiesHave MoreFunMeowMeow M eowPussiesHaveM oreFunMeowMeowM
eowPussiesHaveM oreFunMeowMeow MeowPussiesHa veMoreFunMeowMe ow
MeowPussiesHave MoreFunMeow MeowMeow PussiesHaveMore Fun
MeowMeowMeowPus si esHa veMoreFunMeowMe owMe
owPussiesHaveMo reF unMeowMeowM eowPussiesHaveM oreFu
nMeowMeowMeowPu ssie sHaveMoreFunMe owMeowMeowPussi esHav
eMoreFunMeowMeo wMeo wPussiesHaveMor eFu nMeowMeowMeowPu ssie
sHaveMoreFunMeo wMeo wMeowPussiesHav eMoreFu nMeowMeowMeowPu ssi
esHaveMoreFunMe owM eowMeowPussiesH aveMoreFu nMeowMeowMeowPu ss
iesHaveMoreFunM e owMeowMeowPussi esHaveMoreFu nMeowMeowMeowP
ussiesHaveMor eFunMeowMeowMeo wPussiesHaveMor e FunMeowMeow
MeowPussi esHaveMoreFunMe owMeowMeowPussi esHave MoreF
unMe owMeowM eowPuss
iesHave MoreF unMeowMeowM
eowPussies Ha veMoreFunMeo
wMeowMeowP us si esHaveMoreFu
nMeowMeowM eow Pus siesHaveMore
FunMeowMeo wMeow Pussi esHaveMoreFu
nMeowMeow MeowPu ssiesH aveMoreFun
Meow MeowMeow Pussie
sHaveMoreFunMeo wMeowMeowPussie sHaveM
oreFunMeowMeowM eowPussiesHaveM o
reFunMeowMeowMe owPussies
Nov 14 '05 #3
On Mon, 04 Oct 2004 22:19:10 -0500, Jack Klein <ja*******@spam cop.net>
had a scratch and wrote:
On Mon, 4 Oct 2004 22:41:52 -0400, Brian Sammon
<us****@brisam mon.fastmail.fm > wrote in comp.lang.c:
According to my programming textbook, "int a;" at the top level of a
file is a definition which shouldn't go in a header file.
However, I'm running into a lot of online documentation that treats that
kind of statement as a declaration that can be in a header file used in
multiple compilation units.
Which of these is correct? Is this something that has changed between
different standards?

What kind of online documentation? What reason do you have to trust
its quality? If this documentation talks about using a declaration
like:

int a;

...without either the 'static' or 'extern' keywords at file scope, the
documentatio n is just plain wrong, and nothing has changed in
different versions of the C standard in this regard.

At file scope a definition like:

int a; /* no initializer */

...is called a 'tentative definition'. The identifier 'a' is declared
with file scope to have static storage duration, int type, and
external linkage. There may be more than one tentative definition for
the same identifier at file scope, as long as they all apply to the
same object type:

When there is a tentative definition in the file, one of two things
happens.

1. There is a later definition with an initializer (called an
'external definition'):

int a = 42;

2. There is no external definition, that is file scope declaration
with an initializer. In this case, at the end of the translation
unit, the compiler will act as though an external definition with an
initializer of 0 existed.

According to the C standard, you produce undefined behavior and C
takes no responsibility for the results by defining an object with
external linkage in multiple translation units. The standard states
that for each external object that is actually referenced in a
program, there must be exactly one definition.

It just so happens that there are some compiler/linker combinations
that allow this, as long as no more than one source file contains an
initializer for the object.

A but it's a little bit more complex than that. K&R C says if you put
extern first then the presence or absence of an initializer makes no
difference - it's always an allusion.

It also happens that there are other
compiler/linker combinations that will reject the program even if none
of the source files contains an initializer.

In any case, it is specifically invalid and non-portable.

=============== ======

Pussie sHaveMo
reFunMeow MeowMeowPus
siesHaveMore FunMeowMeowMeo
wPussiesHaveMo reFunMeowMeowMe o
wPussiesHaveMor eFunMeowMeowMeo wP
ussiesHaveMoreF u nMeowMeowMeowPu ssi
esHaveMoreFunMe o wMeowMeowPussie sHav
eMoreFunMeowMeo wM eowPussiesHaveM or
eFunMeowMeowMeo wP ussiesHaveMoreF unM
eowMeowMeowPuss ie sHaveMoreFunMeo wMe owMeowPus
siesHaveM oreFunMeowMeowM e owPussiesHaveMo re FunMeowMeowMe
owPussiesHave MoreFunMeowMeow M eowPussiesHaveM oreFunMeowMeowM
eowPussiesHaveM oreFunMeowMeow MeowPussiesHa veMoreFunMeowMe ow
MeowPussiesHave MoreFunMeow MeowMeow PussiesHaveMore Fun
MeowMeowMeowPus si esHa veMoreFunMeowMe owMe
owPussiesHaveMo reF unMeowMeowM eowPussiesHaveM oreFu
nMeowMeowMeowPu ssie sHaveMoreFunMe owMeowMeowPussi esHav
eMoreFunMeowMeo wMeo wPussiesHaveMor eFu nMeowMeowMeowPu ssie
sHaveMoreFunMeo wMeo wMeowPussiesHav eMoreFu nMeowMeowMeowPu ssi
esHaveMoreFunMe owM eowMeowPussiesH aveMoreFu nMeowMeowMeowPu ss
iesHaveMoreFunM e owMeowMeowPussi esHaveMoreFu nMeowMeowMeowP
ussiesHaveMor eFunMeowMeowMeo wPussiesHaveMor e FunMeowMeow
MeowPussi esHaveMoreFunMe owMeowMeowPussi esHave MoreF
unMe owMeowM eowPuss
iesHave MoreF unMeowMeowM
eowPussies Ha veMoreFunMeo
wMeowMeowP us si esHaveMoreFu
nMeowMeowM eow Pus siesHaveMore
FunMeowMeo wMeow Pussi esHaveMoreFu
nMeowMeow MeowPu ssiesH aveMoreFun
Meow MeowMeow Pussie
sHaveMoreFunMeo wMeowMeowPussie sHaveM
oreFunMeowMeowM eowPussiesHaveM o
reFunMeowMeowMe owPussies
Nov 14 '05 #4
In article <n6************ *************** *****@4ax.com>,
Bradley Bungmunch <br************ ***@yahoo.com > wrote:
extern int a; /* an allusion to a - it tells the compiler to look
elsewhere for the definition - that's what you'd expect in a header
file *./
Note that that "elsewhere" might be later in the file (but, for a header,
shouldn't be).

int a; /* a tentative definition or an allusion - it's up to the
compiler to decide on the basis of what's elsewhere in the source file
*/
The "what's elsewhere in the source file" (translation unit, to be
precise) here is fairly straightforward : If there's no "true" definition
(one that actually allocates storage), this becomes one, otherwise
it doesn't.

int a=0; /* a real definition */
ANSI, K&R, and Unix all have different strategies for resolving
tentative definitions, allusions, and real declarations.


C requires that there be at most one "true" definition for each
identifier; having more than one in the same translation unit is
a constraint violation, and having more than one across different
translation units invokes undefined behavior.

Some implementations handle this particular type of undefined behavior
by reporting an error at link time; others silently ignore multiple
definitions and treat them as simply references to the same object (which
makes things work as expected if they're the same type, and introduces
Interesting errors otherwise); others can have more creative ways of
dealing with this.

[snip 40 lines]

Isn't alt.fan.warlord the appropriate newsgroup to crosspost to with
oversized .sigs?
dave

--
Dave Vandervies dj******@csclub .uwaterloo.ca
Maybe I should add a line that says, "No matter what you do, it is sure
to annoy at least one of the regulars".
--Billy Chambless in comp.lang.c
Nov 14 '05 #5
Jack Klein <ja*******@spam cop.net> wrote:

int a;

...without either the 'static' or 'extern' keywords at file scope, the
documentation is just plain wrong, and nothing has changed in
different versions of the C standard in this regard.
I'm not sure what you mean by "plain wrong". The rest of
your message explains how it is a tentative definition
(which is surely a correct usage). Of course it is wrong
to have 2 different objects with external linkage but the same
name.

I use this in my code sometimes:
STATIC int a;
the point being that if the object has internal linkage then
it doesn't show up in the map file and I don't know its address
so I can't inspect it in the (non-integrated) debugger.
So I can define STATIC as nothing while debugging, and then
define it as 'static' for the release version.
Of course I attempt to choose more unique names than 'a'.
2. There is no external definition, that is file scope declaration
with an initializer. In this case, at the end of the translation
unit, the compiler will act as though an external definition with an
initializer of 0 existed.


Unfortunately I've encountered many (non-standard of course)
embedded compilers that don't initialize the variable to 0.
Does this match your experience?
(I'm now in the habit of specifically initializing all my
file-scope variables, then the linker puts them in a different
section and they get initialized correctly).
Nov 14 '05 #6
"Old Wolf" <ol*****@inspir e.net.nz> wrote in message
news:84******** *************** ***@posting.goo gle.com...
Of course I attempt to choose more unique names than 'a'.
But..., doesn't that make your code easier to understand?
(I'm now in the habit of specifically initializing all my
file-scope variables, then the linker puts them in a different
section and they get initialized correctly).


But..., don't you lose the "Surprise!" factor?

It all sounds very planned out and boring...

--
Mabden
Nov 14 '05 #7
On 7 Oct 2004 14:55:28 -0700
ol*****@inspire .net.nz (Old Wolf) wrote:
Jack Klein <ja*******@spam cop.net> wrote:

int a;

...without either the 'static' or 'extern' keywords at file scope,
the documentation is just plain wrong, and nothing has changed in
different versions of the C standard in this regard.


I'm not sure what you mean by "plain wrong". The rest of
your message explains how it is a tentative definition
(which is surely a correct usage). Of course it is wrong
to have 2 different objects with external linkage but the same
name.

I use this in my code sometimes:
STATIC int a;
the point being that if the object has internal linkage then
it doesn't show up in the map file and I don't know its address
so I can't inspect it in the (non-integrated) debugger.
So I can define STATIC as nothing while debugging, and then
define it as 'static' for the release version.
Of course I attempt to choose more unique names than 'a'.


You need a better debugger. Most of the debuggers I've used with In
Circuit Emulators and simulators could cope with static and local
variable. Of course, you probably don't have any choice in debuggers :-(
2. There is no external definition, that is file scope declaration
with an initializer. In this case, at the end of the translation
unit, the compiler will act as though an external definition with an
initializer of 0 existed.


Unfortunately I've encountered many (non-standard of course)
embedded compilers that don't initialize the variable to 0.
Does this match your experience?
(I'm now in the habit of specifically initializing all my
file-scope variables, then the linker puts them in a different
section and they get initialized correctly).


I've had this problem as well. My solution was to reset all memory to
all bits zero during a RAM test that was done at power up in the
startup code (i.e. as part of initialising the C environment).
--
Flash Gordon
Sometimes I think shooting would be far too good for some people.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #8

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

Similar topics

5
3224
by: A | last post by:
Hi, Consider this code: //Header File - Foo.h int i = 0; // non-static global variable class Foo{ ...
10
2645
by: Kleenex | last post by:
Reason: I am working on an embedded project which has very limited memory (under 512 bytes, 60 or so of which is stack space), which translates into limited stack space. In order to save on stack space, I tried to only use parameters and stack space for things which are truely temporary. Instead of passing a pointer to a data structure which should always be populated with data, I have the data structure declared as a global variable and...
7
3146
by: Michael | last post by:
Hi newsgroup, as the subject indicates I am looking for an advice using global variables. I am not if this problem is more about style then C. If its wrong in thi group, sorry. So I have a couple of function that all need the same information (all located in the same file). By now it looks like /* file beginns */
18
8654
by: vib | last post by:
Hi there, By chance, I came to learn that it is bad programming practice to initialize global variables at outside of programs. Is it that bad? In order to fullfil this, I had to declare them with const, but thereafter they are no longer variables. Just couldn't see the benefits of this practice. Any comments or advices are welcome. Thanks vib
9
5524
by: John Smith | last post by:
I want to share a variable between multiple forms in a Windows app. Where do I declare the variable ? I came up with one way that is to declare it as a member of the MainForm, and then access it using ((MainForm)Application.OpenForms).<MyVariableName>. Is there a more elegant or better way? Btw, the variable I'd like to share is an open SqlConnection.
10
7034
by: Jay Wolfe | last post by:
Hello, I'm trying to make sure I use best practices (and hence save myself some headaches) with the declaration and definition of global variables. Let's say I have an app with 30 files, including main.cpp I have global variables that need defining in main.cpp and declaring in all other files in. The way I've seen it done is to define/declare everything in one header file (e.g. globalincludes.h) prefaced with the word EXTERN ...
9
8662
by: CDMAPoster | last post by:
About a year ago there was a thread about the use of global variables in A97: http://groups.google.com/group/comp.databases.ms-access/browse_frm/thread/fedc837a5aeb6157 Best Practices by Kang Su Gatlin, casual mention was made about using static variables as an alternative to using global variables. This caused me to think of the following: '-----Begin module code
1
1767
by: razael1 | last post by:
Hi, I am declaring a global variable in a .h file like this: extern MyClass object; Then I include the .h file in other files and try to use object. I get "object not declared", but then when I add: MyClass object;
1
29387
weaknessforcats
by: weaknessforcats | last post by:
C++: The Case Against Global Variables Summary This article explores the negative ramifications of using global variables. The use of global variables is such a problem that C++ architects have called it polluting the global namespace. This article explores what happens when the global namespace becomes polluted and how to avoid this condition. The opinions expressed in this article are those of the author alone although many have...
0
9686
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
10250
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
10222
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
10026
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
9068
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
7564
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
6805
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
5463
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...
1
4139
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.