473,657 Members | 2,585 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Global variable declaration in headers

Can someone explain the scope/linkage differences between the following 4
global declarations and when one should be used (theoretically) over the
rest?

sample.h
---------
#ifndef SAMPLE_H
#define SAMPLE_H

int a;
const int b;
static int c;
extern int d;

#endif
---------

And if I gave 'd' an initial value, what the consequences would be (if any)?
Nov 14 '05 #1
7 2587
Method Man wrote:
Can someone explain the scope/linkage differences between the following 4
global declarations and when one should be used (theoretically) over the
rest?

sample.h
---------
#ifndef SAMPLE_H
#define SAMPLE_H

int a;
Reserve sizeof(int) bytes for a in the uninitialized variables section,
that at program startup will be set to zero. This definition will be
used *unless* some other definition appears like:
int a = 78;
If the second definition appears anywhere in the program, it will be
used instead of this one.
const int b; Same as previously but now b can't be assigned to. static int c; Same as the first definition but the name "c" will not be visible
in other modules of the program. extern int d; This integer variable is defined somewhere else as an external, and
is used in this module. And if I gave 'd' an initial value, what the consequences would be (if any)?


int a = 78;
Reserve sizeof(int) byte in the data section and fill it with the bit
pattern 78. This is definitive, no other definition can follow.
const int b = 78;
Same as above but the value of b can't be changed.
Some compilers will optimize:
static const int b = 78;
so that all references of this "variabl" will be replaced with 78.

static int c=78;
Same as the first one except that the name is not visible elsewhere.

extern int d = 78;
This is equivalent to the first definition, int d = 78;
Nov 14 '05 #2
Method Man wrote:

Can someone explain the scope/linkage
differences between the following 4
global declarations and when one should be used
(theoretically) over the rest?

sample.h
---------
#ifndef SAMPLE_H
#define SAMPLE_H

int a;
const int b;
static int c;
extern int d;

#endif
---------
d is the only one of those declarations that belongs in a header file.
d should also be declared in one of the C files in the C program,
like sample.c.
Having static c in the header file,
defeats the whole point of the static keyword.
Every C file which #includes sample.h,
will have it's own a, b and c, that the other C files don't know about.
And if I gave 'd' an initial value,
what the consequences would be (if any)?


If you did that, then you wouldn't be able to declare d
in a C file which #included sample.h.

--
pete
Nov 14 '05 #3
Groovy hepcat Method Man was jivin' on Sun, 10 Oct 2004 02:02:09 -0400
in comp.lang.c.
Global variable declaration in headers's a cool scene! Dig it!
Can someone explain the scope/linkage differences between the following 4
global declarations and when one should be used (theoretically) over the
rest?

sample.h
---------
#ifndef SAMPLE_H
#define SAMPLE_H

int a;
File scope and external linkage.
const int b;
File scope and external linkage.
static int c;
File scope and internal linkage.
extern int d;
File scope and external linkage.
#endif
---------

And if I gave 'd' an initial value, what the consequences would be (if any)?


It would become a definition. Definitions are bad in a header.
Headers should contain declarations, not definitions.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technicall y correct" English; but since when was rock & roll "technicall y correct"?
Nov 14 '05 #4
Hiho,
pete wrote:
Method Man wrote:
[snip header-file]
static int c;

[snip] Having static c in the header file,
defeats the whole point of the static keyword.


Not necessarily. You can for example use a header for
testing/extended error state returns and so on and count
the number of errors encountered/store error states and
so on. In order to make sure that the translation units
or modules do not get confused, you use static variables.
I have seen similar mechanisms in large code.
However, if possible I'd rather make do without as it
certainly does not enhance clarity...
Cheers
Michael

Nov 14 '05 #5
Michael Mair wrote:

Hiho,

pete wrote:
Method Man wrote:
>

[snip header-file]
static int c;

>

[snip]
Having static c in the header file,
defeats the whole point of the static keyword.


Not necessarily. You can for example use a header for
testing/extended error state returns and so on and count
the number of errors encountered/store error states and
so on. In order to make sure that the translation units
or modules do not get confused, you use static variables.
I have seen similar mechanisms in large code.


I don't understand how that header file is used, and how there
would be a benefit from having a static object declaration in it.
What would a program that used it, be like?
Which C files would include it, in a program?
How many C files would there be in a program which used it.

--
pete
Nov 14 '05 #6
Hi pete,

sorry for getting back to you only now (busy today, so answers
which require much thought take longer)
pete wrote:
Michael Mair wrote:
Hiho,

pete wrote:
[snip]
Having static c in the header file,
defeats the whole point of the static keyword.
Not necessarily. You can for example use a header for
testing/extended error state returns and so on and count
the number of errors encountered/store error states and
so on. In order to make sure that the translation units
or modules do not get confused, you use static variables.
I have seen similar mechanisms in large code.


I don't understand how that header file is used, and how there
would be a benefit from having a static object declaration in it.


As I said in the snipped part, I do not think it is a good
technique. I do no longer have access to the code but an
untested sample header file could look like that:

#ifndef CATCH_ERROR
#define CATCH_ERROR

#include <stddef.h> /* for size_t */

/* error states */
enum ce_errortypes {
CE_OK=0,
CE_INVALID_INPU T,
/* Easy checks ^ */
CE_START_BAD_ER RORS,
/* Bad Errors v */
CE_INVALID_OP,
CE_INVALID_RANG E,
CE_END
};

static unsigned long int ce_statecounter s[(size_t)CE_END+ 1];

#ifdef COUNT_ERRORS
# define RETURN(ret_int) \
{ ce_statecounter s[( (ret_int) >= 0 && (ret_int)< CE_END \
&& (int)(ret_int)= =(ret_int) ) \
? (int)(ret_int) : CE_END] += 1; \
return (ret_int);}
#else
# define RETURN(ret_int) return (ret_int);
#endif

#define HOW_MANY_CHECK_ ERRORS(num) {enum ce_errortypes counter;\
(num) = 0; for(counter=1;c ounter<CE_START _BAD_ERRORS;\
counter++) {(num) += ce_statecounter s[counter];}}
#define HOW_MANY_BAD_ER RORS(num) {enum ce_errortypes counter;\
(num) = CE_START_BAD_ER RORS+1; for(counter=1;\
counter<CE_END; counter++)\
{(num) += ce_statecounter s[counter];}}
#define HOW_MANY_STRANG E_ERRORS(num) (num) = ce_statecounter s[CE_END]

#endif

It is right now only for (non-negative) int returns but I did
not bother wo write more tests and mapping and so on.
The functions return 0/CE_OK on success and you do
if (ret=fun1(....) )
RETURN(..approp riate error value..);

You just include the header for the files you want to test and use
RETURN instead of return.
In your test routine or somewhere else you just find out
about the types of encountered errors by using HOW_MANY_..._ER RORS

It can come in handy for simulation software where you do not
necessarily have convergence in every step; so you just count the
"not converged" errors and decide based on that number whether
the result is acceptable or whether you suspect that the result
and the repercussions if wrong might get your customers to want
you to pay for the damage...

You make ce_statecounter s static because you only want to count
it per file.

What would a program that used it, be like?
Ugly. I think this is answered above.
Which C files would include it, in a program?
Those which need this kind of treatment?
I am not trying to be evasive but I am not sure what you want to
know. In the example with the simulation software, typically
the high level solver routines and the matrix assembly would use
that kind of stuff.
How many C files would there be in a program which used it.


42.
Honestly, are you kidding?
--Michael

Nov 14 '05 #7
Michael Mair wrote:

Hi pete,

sorry for getting back to you only now (busy today, so answers
which require much thought take longer)

pete wrote:
Michael Mair wrote:
Hiho,

pete wrote:
[snip]

Having static c in the header file,
defeats the whole point of the static keyword.

Not necessarily. You can for example use a header for
testing/extended error state returns and so on and count
the number of errors encountered/store error states and
so on. In order to make sure that the translation units
or modules do not get confused, you use static variables.
I have seen similar mechanisms in large code.
You make ce_statecounter s static because you only want to count
it per file.


Thank you.

--
pete
Nov 14 '05 #8

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

Similar topics

5
3215
by: A | last post by:
Hi, Consider this code: //Header File - Foo.h int i = 0; // non-static global variable class Foo{ ...
3
6431
by: Eric Lilja | last post by:
Hello, I have a few global variables in my program. One of them holds the name of the application and it's defined in a header file globals.hpp (and the point of definition also happen to be the point of declaration of this variable, correct?): static const char * g_application_name = "Tiny, class-based MDI Example"; In another source file, I'm including the header globals.hpp and I'm using the variable g_application_name. I do,...
2
8821
by: Thomas Matthews | last post by:
Hi, I'm getting linking errors when I declare a variable in the global scope, but not inside a function. The declarations are the same (only the names have been changed...). class Book { public: Book()
6
19053
by: rick | last post by:
Noob problem. I prefer to keep all my scripts in an external '.js' file. I am currently loading the external '.js' file from the header. Problem is I would like to declare a global variable in the external file, but I keep getting an error about the object does not exist. Can someone tell me where or how to declare a global variable in an external file that is available after the page is loaded.
7
3129
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 */
44
3609
by: fabio | last post by:
Why? i' ve heard about this, the usage of global vars instead of locals is discouraged, but why? thx :)
16
3215
by: Roman Ziak | last post by:
Hello, there were times when I used to be looking for a way to access JavaScript Global object similar to those found in VBScript or PHP ($GLOBALS). At present this has only academic value for me. I was doing research on JavaScript inheritance recently (simplifying it in particular) and after reading 10.1.1, 10.1.3 and some other sections of ECMA262 I got a hint on accessing global object from different than global scope.
4
7102
by: the_init | last post by:
Hi friends, Can you please explain me why the following code prints 10, instead of 20 - Here I am little confused with the static and global declaration of i in the same program. #include<stdio.h> int i;
112
5423
by: istillshine | last post by:
When I control if I print messages, I usually use a global variable "int silent". When I set "-silent" flag in my command line parameters, I set silent = 1 in my main.c. I have many functions that may print some messages. foo(...) { if (!silent)
0
8397
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
8310
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8827
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
8732
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...
0
8605
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
5632
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
4315
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2731
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
2
1620
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.