473,763 Members | 1,883 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

extern const variable in case label

Hello NG

I have the following code:
file1.h:

static const int iValue = 5;

<EOF>
file2.cpp

#include <iostream>
#include "file1.h"

int main(int args, char* argv[])
{
switch(args) {
case iValue:
std::cout << "Hello\n";
}
}

<EOF>

This works fine as the value of the constant "iValue" is known when
compiling the main()-function in file2.cpp.
I have some more cpp-files which include file1.h. Therefore I have a copy of
"iValue" in each translation unit as it has internal linkage. In the
executable which is made with these object files (translation units) I have
several copies of that variable; all having the same value.

Now, I would like to change the linkage of "iValue" to extern so that there
is only one symbol for this constant in my executable.
When I change the keyword "static" to "extern" I have the problem that the
symbol is more than once defined in my executable.
When I only declare the variable "iValue" in file1.h with external linkage
("extern const int iValue;") and define it in a new file called file1.cpp
("extern const iValue = 5;"), then I have no problem with multiple
definitions but I have a new problem in my function main() because the value
of "iValue" is not known when compiling file2.cpp.

Do you have any suggestions how I can compile all my code without having
more than one symbol for "iValue" in my program? Or is it not possible what
I am trying to reach?
Thanks for all your answers in advance,
Chris
Oct 2 '08
21 2759
IIRC, just
const int iValue = 5;
no 'static', no 'extern'
IIRC, constants in the file scope have internal linkage (in C++).
Oct 3 '08 #11
On Oct 3, 7:49 am, "Christian Meier" <chris@no_spam. comwrote:
"James Kanze" <james.ka...@gm ail.comwrote:
With my compiler and linker I have these symbols over 10
000 times in my executable and I was able to reduce the
program size a bit with changing these constants to extern
which are not used in case labels.
That is strange. I've yet to see a compiler where they'd
take any space at all, as long as their address wasn't
taken.
Eventually my assumption was wrong about the more than 10 000
symbols for this variable.... And I have not checked whether
the address is taken.
<Offtopic: UNIX Commands and Compiler version>
But the command "nm MyExecutable | grep iValue | wc -l" has
the output "11059" at this moment.
We use GCC 4.1.0...
</Offtopic>
Interesting. I would have thought 0 occurances (or at most,
only for those where the address was being taken). It's
possible that in debug mode, g++ would generate them, since you
could presumable modify the value with a debugger, but a quick
check with a single module on my system (g++ 4.1.0 under Solaris
and Linux) didn't reveal them. Even in debug mode: "nm a.out |
grep staticConst" (where the actual variable was named
staticConst) didn't have any output. Sun CC did generate the
object in debug mode (as a global, no less, but with a funny
prefix added to the name, presumably to make it distinct), but
not when optimizing was turned on.

I'm curious. If you compile the following program:

static int const staticConst = 42 ;

int
main()
{
return staticConst ;
}

then do "nm a.out | grep staticConst", what do you get (with and
without optimizing)?

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Oct 3 '08 #12
On Oct 3, 4:56 am, Barry <dhb2...@gmail. comwrote:

[...]
const int iValue = 5;
no 'static', no 'extern'
Both:
int const iValue = 5 ;
and
static int const iValue = 5 ;
mean exactly the same thing to the compiler. The choice of
which one to use is largely an issue of style; some people
prefer making the internal linkage explicit.

This is also one point where C and C++ are not compatible. If
the code is to be used in a header used in both languages, then
the static is necessary.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Oct 3 '08 #13
"James Kanze" <ja*********@gm ail.comwrote:
On Oct 3, 7:49 am, "Christian Meier" <chris@no_spam. comwrote:
"James Kanze" <james.ka...@gm ail.comwrote:
With my compiler and linker I have these symbols over 10
000 times in my executable and I was able to reduce the
program size a bit with changing these constants to extern
which are not used in case labels.
That is strange. I've yet to see a compiler where they'd
take any space at all, as long as their address wasn't
taken.
Eventually my assumption was wrong about the more than 10 000
symbols for this variable.... And I have not checked whether
the address is taken.
<Offtopic: UNIX Commands and Compiler version>
But the command "nm MyExecutable | grep iValue | wc -l" has
the output "11059" at this moment.
We use GCC 4.1.0...
</Offtopic>

Interesting. I would have thought 0 occurances (or at most,
only for those where the address was being taken).
I don't know in which cases the address is needed. I suppose there are many
other situations than "&iValue".
What about passing it to a function which takes a "const int&" as parameter?
If references are implemented as pointers than the address is needed for
this.
Using this variable in such a way is not unusual in our project. Could this
be the reason for all (or at least almost) the symbols in my executable?

It's possible that in debug mode, g++ would generate them, since you
could presumable modify the value with a debugger, but a quick
check with a single module on my system (g++ 4.1.0 under Solaris
and Linux) didn't reveal them. Even in debug mode: "nm a.out |
grep staticConst" (where the actual variable was named
staticConst) didn't have any output. Sun CC did generate the
object in debug mode (as a global, no less, but with a funny
prefix added to the name, presumably to make it distinct), but
not when optimizing was turned on.

I'm curious. If you compile the following program:

static int const staticConst = 42 ;

int
main()
{
return staticConst ;
}

then do "nm a.out | grep staticConst", what do you get (with and
without optimizing)?
I don't get any output for this.

But for an extended version of your code, I got an indication:

$ cat main.cpp
#include <iostream>

static int const staticConst = 42;

void func(const int& ri)
{
std::cout << ri << '\n';
}

int main()
{
func(staticCons t);
return staticConst ;
}
$ g++ -o main main.cpp
$ nm main | grep staticConst
000000000040093 8 r staticConst
$ g++ -O3 -o main main.cpp
$ nm main | grep staticConst
$

Compiling this code without an explicit optimization level results in having
1 symbol staticConst. However, we are compiling everything with -O3.
Oct 3 '08 #14
"Christian Meier" <chris@no_spam. comwrote in
news:bb******** *************** ***@news.hispee d.ch:
>
But for an extended version of your code, I got an indication:

$ cat main.cpp
#include <iostream>

static int const staticConst = 42;

void func(const int& ri)
{
std::cout << ri << '\n';
}

int main()
{
func(staticCons t);
return staticConst ;
}
$ g++ -o main main.cpp
$ nm main | grep staticConst
000000000040093 8 r staticConst
$ g++ -O3 -o main main.cpp
$ nm main | grep staticConst
$

Compiling this code without an explicit optimization level results in
having 1 symbol staticConst. However, we are compiling everything with
-O3.
In its simplest form, the reference takes the address of the variable and
thus you get a symbol. With the optimizer turned on, it probably inlines
the function and you no longer need the variable, thus you don't see it
with -O3.

joe
Oct 3 '08 #15
On Oct 2, 6:05*pm, "Christian Meier" <chris@no_spam. comwrote:
well. I think you should keep in mind that the case value can only be
constant integral values.

What do you exactly mean with this? Isn't "extern const int iValue" a
constant integral value?
I guess the compiler will complain because ("extern const int
iValue;") is not known until linking while you should specify its
value in compile time because the "case" statement needs it.

I think you can just declare "const int iValue = 5;" in file1.h, and
use the "#ifndef .. #define.. #endif" thing to avoid multiple
inclusion.

In other files where "iValue" is used, you can just include "file1.h"
and it should work.
Oct 3 '08 #16
On Oct 3, 1:33 pm, "Christian Meier" <chris@no_spam. comwrote:
Interesting. I would have thought 0 occurances (or at most,
only for those where the address was being taken).
I don't know in which cases the address is needed. I suppose
there are many other situations than "&iValue". What about
passing it to a function which takes a "const int&" as
parameter? If references are implemented as pointers than the
address is needed for this. Using this variable in such a way
is not unusual in our project. Could this be the reason for
all (or at least almost) the symbols in my executable?
Technically, the rule is that an instance of the variable is
needed if the variable is used in any context where there is not
an immediate lvalue to rvalue conversion. Practically, in the
case of const values, that means taking its address or using it
to initialize a reference. (I can't think of any other cases
which would be legal with a const variable, but I could have
forgotten some.)

A second rule sometimes comes into play: the "as if" rule.
Basically, given a legal program, the compiler can do anything
it wants, as long as the observable behavior of the program is
"as if" it followed the abstract semantics. Thus, if you pass
the value by reference to an inline function, the compiler is
likely able to optimize away the use of the reference, and not
generate the instance. The observable behavior of your code
would not change. I expect that most compilers do this as well,
if they actually inline the function.

And just curious, but why are you passing int's by const
references?
It's possible that in debug mode, g++ would generate them, since you
could presumable modify the value with a debugger, but a quick
check with a single module on my system (g++ 4.1.0 under Solaris
and Linux) didn't reveal them. Even in debug mode: "nm a.out |
grep staticConst" (where the actual variable was named
staticConst) didn't have any output. Sun CC did generate the
object in debug mode (as a global, no less, but with a funny
prefix added to the name, presumably to make it distinct), but
not when optimizing was turned on.
I'm curious. If you compile the following program:
static int const staticConst = 42 ;
int
main()
{
return staticConst ;
}
then do "nm a.out | grep staticConst", what do you get (with and
without optimizing)?
I don't get any output for this.
But for an extended version of your code, I got an indication:
$ cat main.cpp
#include <iostream>
static int const staticConst = 42;
void func(const int& ri)
{
std::cout << ri << '\n';
}
int main()
{
func(staticCons t);
return staticConst ;
}
$ g++ -o main main.cpp
$ nm main | grep staticConst
000000000040093 8 r staticConst
$ g++ -O3 -o main main.cpp
$ nm main | grep staticConst
$
Compiling this code without an explicit optimization level
results in having 1 symbol staticConst. However, we are
compiling everything with -O3.
That's what I explained above. When optimization is turned on,
g++ will inline simple functions anytime it sees the definition.
Even if the function is not declared inline. With the result
that it doesn't ever actually need the instance, and won't
generate it.

In most cases, about the only time you'll have references to a
const int is as a result of template instantiation (and even
then, one could argue that having things like
std::vector<>:: push_back take a T const&, rather than simply a
T, is poor design). Because g++ doesn't implement export, that
means that the implementation of the function will be visible.
And because the function has to be in a header file, it should
be small enough that g++ can inline it with -O3.

That's for the theory. In practice, implementations of things
like std::vector<>:: push_back often involve enough levels of
indirection that it's quite possible that g++ doesn't manage to
inline them completely, which could result in what you are
seeing. (The obvious answer then is to get a better compiler
and a better implementation of the library. Easier said than
done---all of the other implementations I know have the same
problems:-).)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Oct 4 '08 #17
"James Kanze" <ja*********@gm ail.comwrote:
On Oct 3, 1:33 pm, "Christian Meier" <chris@no_spam. comwrote:
Interesting. I would have thought 0 occurances (or at most,
only for those where the address was being taken).
I don't know in which cases the address is needed. I suppose
there are many other situations than "&iValue". What about
passing it to a function which takes a "const int&" as
parameter? If references are implemented as pointers than the
address is needed for this. Using this variable in such a way
is not unusual in our project. Could this be the reason for
all (or at least almost) the symbols in my executable?

Technically, the rule is that an instance of the variable is
needed if the variable is used in any context where there is not
an immediate lvalue to rvalue conversion. Practically, in the
case of const values, that means taking its address or using it
to initialize a reference. (I can't think of any other cases
which would be legal with a const variable, but I could have
forgotten some.)

A second rule sometimes comes into play: the "as if" rule.
Basically, given a legal program, the compiler can do anything
it wants, as long as the observable behavior of the program is
"as if" it followed the abstract semantics. Thus, if you pass
the value by reference to an inline function, the compiler is
likely able to optimize away the use of the reference, and not
generate the instance. The observable behavior of your code
would not change. I expect that most compilers do this as well,
if they actually inline the function.
Ok, thanks a lot! I think this is the explanation I was looking for.

And just curious, but why are you passing int's by const
references?
I can't tell you for sure but I think the people in this company do it
because it was in the coding guidelines some years ago. The rule was removed
in the meantime but many people still write it this way...

It's possible that in debug mode, g++ would generate them, since you
could presumable modify the value with a debugger, but a quick
check with a single module on my system (g++ 4.1.0 under Solaris
and Linux) didn't reveal them. Even in debug mode: "nm a.out |
grep staticConst" (where the actual variable was named
staticConst) didn't have any output. Sun CC did generate the
object in debug mode (as a global, no less, but with a funny
prefix added to the name, presumably to make it distinct), but
not when optimizing was turned on.
I'm curious. If you compile the following program:
static int const staticConst = 42 ;
int
main()
{
return staticConst ;
}
then do "nm a.out | grep staticConst", what do you get (with and
without optimizing)?
I don't get any output for this.
But for an extended version of your code, I got an indication:
$ cat main.cpp
#include <iostream>
static int const staticConst = 42;
void func(const int& ri)
{
std::cout << ri << '\n';
}
int main()
{
func(staticCons t);
return staticConst ;
}
$ g++ -o main main.cpp
$ nm main | grep staticConst
000000000040093 8 r staticConst
$ g++ -O3 -o main main.cpp
$ nm main | grep staticConst
$
Compiling this code without an explicit optimization level
results in having 1 symbol staticConst. However, we are
compiling everything with -O3.

That's what I explained above. When optimization is turned on,
g++ will inline simple functions anytime it sees the definition.
Even if the function is not declared inline. With the result
that it doesn't ever actually need the instance, and won't
generate it.

In most cases, about the only time you'll have references to a
const int is as a result of template instantiation (and even
then, one could argue that having things like
std::vector<>:: push_back take a T const&, rather than simply a
T, is poor design).
Why is this said to be a poor design? Do you have a link to a document or a
c++-group discussion?
Oct 6 '08 #18
On Oct 6, 8:28 am, "Christian Meier" <chris@no_spam. comwrote:

[...]
In most cases, about the only time you'll have references to
a const int is as a result of template instantiation (and
even then, one could argue that having things like
std::vector<>:: push_back take a T const&, rather than simply
a T, is poor design).
Why is this said to be a poor design? Do you have a link to a
document or a c++-group discussion?
I didn't say that it was poor design, or that it was generally
considered poor design (although IMHO... I'm not sure), but that
one could make an argument that it was poor design. Basically,
it's an optimization; what std::vector<>:: push_back needs is an
object. It's passed as a const reference, rather than by value,
for purely optimization reasons. One could argue that 1) this
is premature optimization, and 2) in the case of things like
std::vector<int or std::vector<dou ble>, it's pessimization, and
that statistically, these are probably the most likely cases
when performance is an issue.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Oct 6 '08 #19
James Kanze wrote:
[...] Basically,
it's an optimization; what std::vector<>:: push_back needs is an
object. It's passed as a const reference, rather than by value,
for purely optimization reasons. One could argue that 1) this
is premature optimization, and 2) in the case of things like
std::vector<int or std::vector<dou ble>, it's pessimization, and
that statistically, these are probably the most likely cases
when performance is an issue.
Since this question came up just a few hours ago:
On my platform (Win32) 'double' is bigger than a 'double&'.
We were discussing whether having to pass less bits to a
function would outweigh the additional indirection. So far
I had assumed that, in general, passing built-in types by
value is the best bet.
What's the foundation of your argument above?

Schobi
Oct 6 '08 #20

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

Similar topics

3
10657
by: Rolf S. Arvidson | last post by:
Be kind, a newb question here. I don't understand why I get a compile-time error from the following: I define a variable in main.cpp as such double x = 1.; int _tmain(int argc, _TCHAR* argv){ ...; }
4
2594
by: John Ratliff | last post by:
I have a few global variables in my app. They are defined in the main application class file and declared (extern) in a header which can be included by anyone who would want to use these variables. Two of the globals are pointers which are initialized at runtime. The others are classes whose values are initialized in the global space. When I had just the pointers, I didn't need to include the extern header in the defining class file. But...
10
6194
by: Mark A. Gibbs | last post by:
I have a question about mixing C and C++. In a C++ translation unit, I want to define a function with internal linkage and C calling convention. Here's a sample of what I want to do: // main.cpp // This is defined in a C module extern "C" void fake_qsort(void*, std::size_t, std::size_t, int (*compare)(const void*, const void*));
18
4287
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.
19
3860
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 object defined in somewhere, and this "somewhere" object does not have the storage-class specifier...
5
16607
by: siliconwafer | last post by:
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 */
17
4933
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
3484
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:
2
2907
by: Shraddha | last post by:
When I read about volatile keyword....while explaning there was an declaration like... extern const a; But as a rule const shoule be initialised where it is defined...but we do ot initialise extern where we declare it....So what is exactly happening here?
0
9566
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
10149
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
10003
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
9943
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
5271
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
5410
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3918
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
3529
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2797
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.