473,545 Members | 2,017 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Use of 'extern' keyword

Hi all,
I wanted to know that is use of extern keyword mandatory in case of
global variables and functions used in other source files?
i.e consider a following piece of code from MSDN explaining extern
storage class:
/*************** *************** *************** *************** ******
SOURCE FILE ONE
*************** *************** *************** *************** *******/

extern int i; /* Reference to i, defined below */
void next( void ); /* Function prototype */

void main()
{
i++;
printf( "%d\n", i ); /* i equals 4 */
next();
}

int i = 3; /* Definition of i */

void next( void )
{
i++;
printf( "%d\n", i ); /* i equals 5 */
other();
}

/*************** *************** *************** *************** ******
SOURCE FILE TWO
*************** *************** *************** *************** *******/

extern int i; /* Reference to i in */
/* first source file */
void other( void )
{
i++;
printf( "%d\n", i ); /* i equals 6 */
}
Here,if I drop the extern keyword from source file 2 and compile and
link the 2 source files I get the same result as with 'extern' keyword.
i.e extern keyword is optional.same is the case with functions.
If so in which cases is the use of 'extern' mandatory?
regards,
-Siliconwafer

Nov 15 '05 #1
5 16595
siliconwafer wrote:
Hi all,
I wanted to know that is use of extern keyword mandatory in case of
global variables and functions used in other source files?
i.e consider a following piece of code from MSDN explaining extern
storage class:
/*************** *************** *************** *************** ******
SOURCE FILE ONE
*************** *************** *************** *************** *******/

extern int i; /* Reference to i, defined below */
void next( void ); /* Function prototype */

void main()
{
i++;
printf( "%d\n", i ); /* i equals 4 */
next();
}

int i = 3; /* Definition of i */

void next( void )
{
i++;
printf( "%d\n", i ); /* i equals 5 */
other();
}

/*************** *************** *************** *************** ******
SOURCE FILE TWO
*************** *************** *************** *************** *******/

extern int i; /* Reference to i in */
/* first source file */
void other( void )
{
i++;
printf( "%d\n", i ); /* i equals 6 */
}
Here,if I drop the extern keyword from source file 2 and compile and
link the 2 source files I get the same result as with 'extern' keyword.
i.e extern keyword is optional.
IIRC any declaration at file scope without an intialization is
considered to be a tentative declaration. This means that if the
compiler encounters the same variable declared more than once it fuses
all the ocurrences into a single global variable. In the case of gcc
you can force this situation to issue a warning. However, if you insist
in using global variables, it's much better practice to define the
variable just once and include it in a header file with the extern
keyword that can be conviniently included in other files as needed.
same is the case with functions.
A function that has no storage class specifier is considered to have
extern class, so they're visible in all compilation units unless
they're explicitly declared to be static, in wich case they're only
visible in the file they're declared.
If so in which cases is the use of 'extern' mandatory?


If you want some global variable defined in another file to be visible
just inside a function (or a block) then you need the extern keyword,
otherwise the declaration would be considered to be a local variable.
Ie:

File a.c:

int a = 0;

File b.c:

void func (void) {
extern int a;
....
}

HTH.

Nov 15 '05 #2
On 28 Jul 2005 03:48:24 -0700, "Antonio Contreras" <an*****@gmail. com>
wrote in comp.lang.c:
siliconwafer wrote:
Hi all,
I wanted to know that is use of extern keyword mandatory in case of
global variables and functions used in other source files?
i.e consider a following piece of code from MSDN explaining extern
storage class:
/*************** *************** *************** *************** ******
SOURCE FILE ONE
*************** *************** *************** *************** *******/

extern int i; /* Reference to i, defined below */
void next( void ); /* Function prototype */

void main()
{
i++;
printf( "%d\n", i ); /* i equals 4 */
next();
}

int i = 3; /* Definition of i */

void next( void )
{
i++;
printf( "%d\n", i ); /* i equals 5 */
other();
}

/*************** *************** *************** *************** ******
SOURCE FILE TWO
*************** *************** *************** *************** *******/

extern int i; /* Reference to i in */
/* first source file */
void other( void )
{
i++;
printf( "%d\n", i ); /* i equals 6 */
}
Here,if I drop the extern keyword from source file 2 and compile and
link the 2 source files I get the same result as with 'extern' keyword.
i.e extern keyword is optional.
IIRC any declaration at file scope without an intialization is
considered to be a tentative declaration. This means that if the
compiler encounters the same variable declared more than once it fuses
all the ocurrences into a single global variable.


Your recollection is partially correct, as far as the C standard is
concerned.

We are talking about declarations of objects at file scope without the
'static' keyword in a translation unit TU (roughly the source code
file and everything it includes). There are four possibilities:

1. Declaration includes 'extern' keyword and has no initializer.

2. Declaration includes 'extern' keyword and has an initializer.

3. Declaration does not have 'extern' keyword and has no initializer.

4. Declaration does not have 'extern' keyword and has an initializer.

Case 1 neither defines nor initializes the object, merely makes it
available for access by code in the TU where it appears. If the code
in the TU does actually reference the object, there must be a
definition of it provided elsewhere when the final program is
assembled. There may be multiple external declarations of this type
for the same object in a TU.

Cases 2 and 4, where an initializer is included in the elaboration,
are completely unambiguous and have exactly the same effect, namely
the definition of the object with external linkage. The presence or
absence of the 'extern' keyword makes no difference at all. This is
called an "external object definition". There may be exactly one such
external object definition of this type for an object in a TU.

Case 3 is the one that often causes confusion. When an object is
declared at file scope without the 'extern' keyword and without an
initializer, it is indeed called a "tentative definition". There may
be multiple tentative definitions of the same object in a TU.

Now here's exactly what the standard says about tentative definitions:

"If a translation unit contains one or more tentative definitions for
an identifier, and the translation unit contains no external
definition for that identifier, then the behavior is exactly as if the
translation unit contains a file scope declaration of that identifier,
with the composite type as of the end of the translation unit, with an
initializer equal to 0."

So the concept of "tentative definition" is only a temporary one
inside a translation unit. Any tentative definition of an object 'x'
will result in an external object definition for 'x', either one with
an initializer in the same translation unit, or an implicit:

object_type x = 0;

....generated by the compiler at the end of the translation unit.

In the OP's case, his first file contains an external object
definition of the int 'i' with an initial value of 3.

If he removes the 'extern' keyword the file scope declaration of 'i'
in the second file, it becomes a tentative definition which at the end
of the file is turned into an external object definition of the int
'i' with an initial value of 0.

If he combines both translation units into a single program, there are
two external object definitions for the int 'i'. This produces
undefined behavior as far as the C standard is concerned.

C has a simple rule for both objects and functions with external
linkage:

If the object or function is not actually referenced in the program,
there may be either 0 or 1 definitions of the object or function.

If the object or function is actually referenced in the program, it
must have exactly 1 external definition.

So omitting the 'extern' keyword from the declaration in the second
file produces undefined behavior. One possible result of undefined
behavior is the program is "working" as the programmer "expects". The
results with another compiler/linker tool set could be quite
different.
In the case of gcc
you can force this situation to issue a warning. However, if you insist
in using global variables, it's much better practice to define the
variable just once and include it in a header file with the extern
keyword that can be conviniently included in other files as needed.
same is the case with functions.


A function that has no storage class specifier is considered to have
extern class, so they're visible in all compilation units unless
they're explicitly declared to be static, in wich case they're only
visible in the file they're declared.
If so in which cases is the use of 'extern' mandatory?


If you want some global variable defined in another file to be visible
just inside a function (or a block) then you need the extern keyword,
otherwise the declaration would be considered to be a local variable.
Ie:

File a.c:

int a = 0;

File b.c:

void func (void) {
extern int a;
...
}

HTH.


The rest of your advice is quite good.

--
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 15 '05 #3
On 28 Jul 2005 03:02:33 -0700, "siliconwaf er" <sp*********@ya hoo.com>
wrote in comp.lang.c:
Hi all,
I wanted to know that is use of extern keyword mandatory in case of
global variables and functions used in other source files?
i.e consider a following piece of code from MSDN explaining extern
storage class:
/*************** *************** *************** *************** ******
SOURCE FILE ONE
*************** *************** *************** *************** *******/

extern int i; /* Reference to i, defined below */
void next( void ); /* Function prototype */

void main()
This is typical Microsoft arrogant, ignorant nonsense. Since they
don't claim conformance to the C standard later than 1995, what you
have when you start a program with "void main()" is totally undefined
behavior, therefore no longer actually a C program at all. At least
the C language standard says nothing at all about what it should or
will do.

But that does not really have anything to do with the issue you are
asking about.
{
i++;
printf( "%d\n", i ); /* i equals 4 */
next();
}

int i = 3; /* Definition of i */

void next( void )
{
i++;
printf( "%d\n", i ); /* i equals 5 */
other();
}

/*************** *************** *************** *************** ******
SOURCE FILE TWO
*************** *************** *************** *************** *******/

extern int i; /* Reference to i in */
/* first source file */
void other( void )
{
i++;
printf( "%d\n", i ); /* i equals 6 */
}
Here,if I drop the extern keyword from source file 2 and compile and
link the 2 source files I get the same result as with 'extern' keyword.
i.e extern keyword is optional.same is the case with functions.
If so in which cases is the use of 'extern' mandatory?
regards,
-Siliconwafer


I went into detail about how the C standard defines this in my
response to Antonio Contreras's reply to your original post.

To summarize, if you remove the 'extern' keyword from the declaration
of 'i' in the second source file, you create an implicit external
definition of 'i' in that translation unit. The first source file has
an explicit external definition of 'i'. If you combine these into one
program, that program has two external definitions of 'i', and that
produces undefined behavior, which literally means that the C standard
washes its hands and doesn't say what should or will happen.

For reasons not worth going into here, on some compilers the program
will build and work the same if you remove the 'extern' keyword in the
second file. On other compilers you will get an error from the linker
and no executable file. I have even seen compilers that will create
different objects for each source file. Changes you make to 'i' in
one file will not change the value of 'i' in the other file.

So to answer your question about when you need the 'extern' keyword,
the C standard says you need it on every file scope declaration of an
object in all the source files of a program, with at most one
exception.

Regardless of how your particular version of your compiler treats this
particular example, if you want your program to build without error
and run with the same results on all C compilers, you need to have the
'extern' in the second file.

There are always dangers in assuming the requirements of the language
from the results of one compiler.

--
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 15 '05 #4
Thanks Jack for such an elaborate reply.I found no book /web defination
that would clear the anamoly.
-Siliconwafer

Nov 15 '05 #5
In article <11************ **********@o13g 2000cwo.googleg roups.com>,
siliconwafer <sp*********@ya hoo.com> wrote:
Thanks Jack for such an elaborate reply.I found no book /web defination
that would clear the anamoly.


I think we can all breathe a sigh of relief at that.

But what is a defination?

What is an anamoly?

Nov 15 '05 #6

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

Similar topics

2
22973
by: Sona | last post by:
Hi, I read some place that if you have two or more modules or files in C, you can share variables between the these modules or files using the 'extern' keyword. I'm not really sure how to do this and when to do this. For example, if main.c has: double some_val; // global and first.c wants to use the variable and the value that was...
18
4260
by: tweak | last post by:
What's the best way to use extern when using multiplefiles that is easiest to maintain? Is it best to declare: extern int a; in a header file and include the header file in all files except where it's defined.
16
1798
by: ooze | last post by:
hi all , anyone could tell me the useage of the keyworkd "extern" in c? and the difference between c & cplusplus? in the C99Rationalv5.10.pdf it lists 4 cases. while the first common cases will incur the vc compiler to complain.
19
3825
by: ccwork | last post by:
Hi all, I am reading "C: A Reference Manual" 4th ed and I get lost for the "extern". It says that global object without specifying the storage-class specifier will have "extern" as the default storage-class specifier. My (little) C experience tells me that an object with "extern" is to let the linker knows that the object is referencing the...
29
448
by: DevarajA | last post by:
Can anyone explain me what extern is used for? I thought it was used to declare variables definited in other files, but i can do that also without extern. /*file a.c*/ int a=5; int main() { f(); }
17
4909
by: Tapeesh | last post by:
I would like to know what is the expected behaviour of C compilers when an extern decleration is intialized. When the following code is compiled using gcc //File extern.c int arr ; int a ;
7
3474
by: MikeF | last post by:
Group, I have a variable declared in 'main.c' as: const unsigned int x = 1; I have another module which uses this same variable, I've tried to declare as:
5
2843
by: Christian Christmann | last post by:
Hi, I've tree questions on the storage class specifier "extern": 1) Code example: int main( void ) { int b = -2; // my line 3 if ( a ) {
16
2300
by: Martin Jørgensen | last post by:
Hi, Problem: ======== Some of my output functions are beginning to take pretty many arguments... I mean.... We're talking about 10-15 arguments :-) So I thought to myself, perhaps this is beginning to get out of hands if I continue to put in extra functionality in the (file-writing) output-functions....
0
7409
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...
0
7664
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. ...
0
7921
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...
0
5982
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...
1
5343
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...
0
3446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1900
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
1
1023
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
720
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...

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.