Hello,
The extern keyword can be used in C and C++
to share global variables between files by
declaring the variable in header file and
defining it in only one of the two files.
For example, if x were not declared
extern in the header file below then
the linker would complain about x
being multiply defined.
--------------------
// main.cpp
#include "hello.h"
int x;
int main() {
x = 0;
hello();
}
--------------------
// hello.h
#ifndef HELLO_H
#define HELLO_H
extern int x;
void hello();
#endif // HELLO_H
--------------------
// hello.cpp
#include <iostream>
#include "hello.h"
void hello() {
std::cout << x << std::endl;
}
----------------------------------
output: 0
----------------------------------
However, I don't quite understand how
using the keyword static in the header
file allows us to define the variable
in the header file and include the
header file in multiple files.
After all, both global variables
and static variables are placed
in the static data segment of a
computer program when loaded
into memory so what is the
difference? Also, why is
1 still being printed in
the second case instead
of 0?
--------------------
// main.cpp
#include "hello.h"
int main() {
x = 0;
hello();
}
--------------------
// hello.h
#ifndef HELLO_H
#define HELLO_H
static int x = 1;
void hello();
#endif // HELLO_H
--------------------
// hello.cpp
#include <iostream>
#include "hello.h"
void hello() {
std::cout << x << std::endl;
}
----------------------------------
output: 1
----------------------------------
Thanks,
JG 14 13453
John Goche wrote:
<snip>
However, I don't quite understand how
using the keyword static in the header
file allows us to define the variable
in the header file and include the
header file in multiple files.
After all, both global variables
and static variables are placed
in the static data segment of a
computer program when loaded
into memory so what is the
difference? Also, why is
1 still being printed in
the second case instead
of 0?
The keyword 'static' declares an object with internal linkage. The
#include just copies and pastes the contents of the header into the
source code. This means you've just defined TWO different objects with
internal linkage - one in each of your translation units. Probably not
what you intended, is it?
Regards,
Bart.
John Goche wrote:
However, I don't quite understand how
using the keyword static in the header
file allows us to define the variable
in the header file and include the
header file in multiple files.
After all, both global variables
and static variables are placed
in the static data segment of a
computer program when loaded
into memory so what is the
difference?
Non static global variables have external linkage, the linker can identify
the variables by his name and resolve his usage from different object
files. The static ones are internal, his names are not exported and can be
used only from the same object file. If you have two static variables with
the same name in different translations units, they are two different
variables. The result is the same if you put it in a header file or in each
of the cpp that include that header, header files are just like some way of
automated copy&paste.
A compiler can use a different build model that the supposed in this
explanation, but the result must be equivalent.
--
Salu2
Julián Albo wrote:
[..]
Non static global variables have external linkage, [..]
Nit-pick: .. unless they are declared 'const'.
Bart <ba***********@ gmail.comwrote:
>The keyword 'static' declares an object with internal linkage. The #include just copies and pastes the contents of the header into the source code. This means you've just defined TWO different objects with internal linkage - one in each of your translation units. Probably not what you intended, is it?
What does the phrase "internal linkage" mean here? It almost
sounds like an oxymoron. What is being linked to what? Does
the linker need to manipulate such a static variable?
Steve
On Mon, 30 Oct 2006 21:33:40 +0000 (UTC), sp*****@speedym ail.org
(Steve Pope) wrote in comp.lang.c++:
Bart <ba***********@ gmail.comwrote:
The keyword 'static' declares an object with internal linkage. The
#include just copies and pastes the contents of the header into the
source code. This means you've just defined TWO different objects with
internal linkage - one in each of your translation units. Probably not
what you intended, is it?
What does the phrase "internal linkage" mean here? It almost
sounds like an oxymoron. What is being linked to what? Does
the linker need to manipulate such a static variable?
Steve
Every identifier in a C++ program has several attributes, and linkage
is one of them. There are exactly three types of linkage, external,
internal, and no linkage.
Internal linkage is defined in the C++ standard like this: "When a
name has internal linkage, the entity it denotes can be referred to by
name from other scopes in the same translation unit."
This differs from identifiers defined at block scope, which cannot be
referred to by name outside of the scope in which it was defined.
--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
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
Jack Klein <ja*******@spam cop.netwrote:
>(Steve Pope) wrote in comp.lang.c++:
>What does the phrase "internal linkage" mean here? It almost sounds like an oxymoron. What is being linked to what? Does the linker need to manipulate such a static variable?
>Every identifier in a C++ program has several attributes, and linkage is one of them. There are exactly three types of linkage, external, internal, and no linkage.
>Internal linkage is defined in the C++ standard like this: "When a name has internal linkage, the entity it denotes can be referred to by name from other scopes in the same translation unit."
>This differs from identifiers defined at block scope, which cannot be referred to by name outside of the scope in which it was defined.
Thanks. I find the choice of words -- "internal linkage" --
un-intuitive, relative to say "local to one source file", but
that's of no consequence here. ;)
Steve
of little
Steve Pope wrote:
[..] I find the choice of words -- "internal linkage" --
un-intuitive, relative to say "local to one source file", but
that's of no consequence here. ;)
It's unintuitive for a newcomer who never dealt with the table
of *external* symbols for a module (no offence intended). What
is the opposite of 'external'? See?
'External' has unfortunately two meanings. And I don't think
there is a way to overcome that. OOH, it's a symbol that cannot
be resolved locally, and as such is deemed to come from outside.
OTOH it's a symbol visible from outside, a symbol to which other
modules can refer (thus for other modules it also is 'external')
by name. 'Internal' is basically the opposite of both of those
meanings, i.e. defined inside and referred inside [the module].
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Victor Bazarov wrote:
Julián Albo wrote:
[..]
Non static global variables have external linkage, [..]
Nit-pick: .. unless they are declared 'const'.
If they are 'const', are they 'variables' !
Geo wrote:
Victor Bazarov wrote:
Julián Albo wrote:
[..]
Non static global variables have external linkage, [..]
Nit-pick: .. unless they are declared 'const'.
If they are 'const', are they 'variables' !
Yes. Technically, the C++ standard defines a 'variable' as being
"introduced by the declaration of an object". That's different than the
mathematical meaning of a 'variable'.
Regards,
Bart. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: ambika |
last post by:
Iam just trying to know "c".
And I have a small doubt about these header files.
The header files just contain the declaration part...Where is the
definition for these declarations written??And how does that get
linked to our program when we run it??I would appreciate any helpful
info..And I would like to thank you for that in advance
-ambika
|
by: Ravi |
last post by:
Hi All:
Is there any reason for declaring functions as static in a header file
if that header file is going to be included in several other files? The
compiler throws a warning for every such function declared but not
called in the source file. Here is what I heard someone mention:
The functions are declared static as an optimization. Making static
"hidden-from-the-user" function to extern to appease -Wall compile
argument is not a good...
|
by: chat |
last post by:
Hi, every body.
I have 3 files like this:
--------------------------------------------------------
file name : header.h
#ifndef TEST_H
#define TEST_H
int a=1;
double b=0.5;
|
by: Christoph Scholtes |
last post by:
Hi,
I have some questions about header files:
Say I have a file functions.c which contains a couple of functions. I
have declared some structs in this file too. The structs are defined in
main.c. Now I create a header file which represents the interface of
functions.c to my main program file main.c.
I put in the header file: all function prototypes with keyword extern
and the declarations of the structs, which are defined in the main...
|
by: John Goche |
last post by:
A common C++ trend is to use
const int foo = 10;
where some C programmers would have used
#define FOO 10
in order to avoid preprocessor overheads.
| |
by: zouyongbin |
last post by:
Stanley B Lippman in his "C++ Primer" that a definition like this
should not appear in a header file:
int ix;
The inclusion of any of these definitions in two or more files of the
same program will result in a linker error complaining about multiple
definitions. So this kind of definition should be avoided as much as
possible. But as we know, the definition of a class is always in a
header file. And we can use "#ifndef" to eliminate...
|
by: wdh3rd |
last post by:
Hi everyone. I'm new to C and I have a few questions:
I am making files for permutations and combinations. Files to be made
are perm.c, perm.h, combo.c, and combo.h.
Since both combinations and permutations use factorial to solve their
problems, factorial is supposed to be in both perm.c and combo.c, and
declared private.
(1) You wouldn't ever put a prototype in a header if that function was
|
by: Stephen Howe |
last post by:
Hi
Just going over some grey areas in my knowledge in C++:
1) If I have
const int SomeConst = 1;
in a header file, it is global, and it is included in multiple translations
units, but it is unused, I know that it does not take up storage in the
|
by: whirlwindkevin |
last post by:
I saw a program source code in which a variable is defined in a header
file and that header file is included in 2 different C files.When i
compile and link the files no error is being thrown.How is this
possible.I thought it will throw "Variable redefinition Error". Giving
the source code for reference.Please help me out on this...
a.h
-----
int g;
void fun(void);
|
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...
|
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,...
| |
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...
|
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...
|
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...
|
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...
|
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();...
|
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...
| |
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
| |