473,397 Members | 1,960 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

Forward declarations to static variables

fox
How do I (portably) make a forward reference to a static (I mean
file-scope) variable?

I've been using "extern" for years, for example:

extern int x;
int foo(void)
{
return x++;
}
static int x = 5;

.... and gcc 3.4.4 and MSVC 2005 do not even warn that anything's wrong
here.

But gcc 4 gives me an error:

static declaration of 'x' follows non-static declaration

It seems that replacing "extern" with "static" makes it happy.

I always thought that "static" means a definition (and not merely a
declaration) for variables
and if you want to just declare a variable then you use "extern". Now I
cannot understand what "static int x;" actually is: just a declaration?
or declaration and definition?
Please note that I can remove the second "static int x" line and it
still compiles...

Can you explain me what C standards say about this issue and why some
compilers don't issue a warning while gcc 4 gives an error? Is it
because some compilers default to C89 and the other default to C9X ?

Thanks,
Piotr

Jan 19 '06 #1
12 12047


fo*@scene.pl wrote On 01/19/06 11:16,:
How do I (portably) make a forward reference to a static (I mean
file-scope) variable?

I've been using "extern" for years, for example:

extern int x;
int foo(void)
{
return x++;
}
static int x = 5;

... and gcc 3.4.4 and MSVC 2005 do not even warn that anything's wrong
here.

But gcc 4 gives me an error:

static declaration of 'x' follows non-static declaration

It seems that replacing "extern" with "static" makes it happy.

I always thought that "static" means a definition (and not merely a
declaration) for variables
and if you want to just declare a variable then you use "extern". Now I
cannot understand what "static int x;" actually is: just a declaration?
or declaration and definition?
Please note that I can remove the second "static int x" line and it
still compiles...

Can you explain me what C standards say about this issue and why some
compilers don't issue a warning while gcc 4 gives an error? Is it
because some compilers default to C89 and the other default to C9X ?


Both versions of the Standard say

If, within a translation unit, the same identifier
appears with both internal and external linkage, the
behavior is undefined.

That's 6.2.2/7 in C99 and 3.1.2.2/7 in Original ANSI (which
ISO renumbered to produce C90).

"The behavior is undefined" implies a couple of things.
First, it means that different compilers are allowed to handle
the situation differently; it can even happen that a single
compiler could handle it inconsistently. Second, it means
that the compiler is not required to complain; any diagnostic
you may receive is just a bonus.

The conclusion: Don't Do That. The duelling declarations
are not valid C, in the sense that C assigns no meaning to
them. Hence, when you write them you have no idea what the
effect might be, no idea what you're asking the compiler to do.

--
Er*********@sun.com

Jan 19 '06 #2
fo*@scene.pl wrote:


I always thought that "static" means a definition (and not merely a
declaration) for variables
and if you want to just declare a variable then you use "extern". Now I
cannot understand what "static int x;" actually is: just a declaration?
or declaration and definition?


It's a declaration and a *tentative* definition. That is, if no actual
definition is found later on in the translation unit, then it will act
as a definition, but it doesn't preclude an actual definition from
appearing later. An actual definition includes an initializer:

static int x; // tentative definition
static int x = 0; // actual definition

-Larry Jones

Any game without push-ups, hits, burns or noogies is a sissy game. -- Calvin
Jan 19 '06 #3

<fo*@scene.pl> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
How do I (portably) make a forward reference to a static (I mean
file-scope) variable?

I've been using "extern" for years, for example:

extern int x;
int foo(void)
{
return x++;
}
static int x = 5;

... and gcc 3.4.4 and MSVC 2005 do not even warn that anything's wrong
here.

But gcc 4 gives me an error:

static declaration of 'x' follows non-static declaration

It seems that replacing "extern" with "static" makes it happy.

I always thought that "static" means a definition (and not merely a
declaration) for variables
and if you want to just declare a variable then you use "extern". Now I
cannot understand what "static int x;" actually is: just a declaration?
or declaration and definition?
Please note that I can remove the second "static int x" line and it
still compiles...

Can you explain me what C standards say about this issue and why some
compilers don't issue a warning while gcc 4 gives an error? Is it
because some compilers default to C89 and the other default to C9X ?

Thanks,
Piotr


Why can't you just move the declaration to the top of the file? For
portability, you'll probably need to remove all references to 'static'.
'static' on variables is supposed to mean that it doesn't get exported to
the linker. However, I've seen some compilers that treat 'static' as
'const' and optimize away the code...
Rod Pemberton
Jan 19 '06 #4
"Rod Pemberton" <do*******@bitbucket.cmm> writes:
[...]
extern int x;
int foo(void)
{
return x++;
}
static int x = 5;
[...] Why can't you just move the declaration to the top of the file? For
portability, you'll probably need to remove all references to 'static'.
'static' on variables is supposed to mean that it doesn't get exported to
the linker. However, I've seen some compilers that treat 'static' as
'const' and optimize away the code...


I can't imagine a compiler treating "static" as "const"; they're
entirely different things. However, if the compiler is able to
determine that the value of x is never modified, it can internally
replace all references to x with a literal value 5 and remove x.
Without the "static", it wouldn't be able to do this, because x could
be referenced from another source file; with "static", the compiler
knows that x exists only within the current source file.

(Even with "static", x could still be modified in another source file
if its address is passed to an external function, or is otherwise made
externally visible. The compiler can still do the optimization if it
can prove that this never happens.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 19 '06 #5
fo*@scene.pl wrote:
How do I (portably) make a forward reference to a static (I mean
file-scope) variable?

I've been using "extern" for years, for example:

extern int x;
int foo(void)
{
return x++;
}
static int x = 5;

... and gcc 3.4.4 and MSVC 2005 do not even warn that anything's wrong
here.

But gcc 4 gives me an error:

static declaration of 'x' follows non-static declaration

It seems that replacing "extern" with "static" makes it happy.

I always thought that "static" means a definition (and not merely a
declaration) for variables
and if you want to just declare a variable then you use "extern". Now I
cannot understand what "static int x;" actually is: just a declaration?
or declaration and definition?
Please note that I can remove the second "static int x" line and it
still compiles...

Can you explain me what C standards say about this issue and why some
compilers don't issue a warning while gcc 4 gives an error? Is it
because some compilers default to C89 and the other default to C9X ?

Thanks,
Piotr


You seem to misunderstand the whole system. Assume a C program written
in two or more translation units (.c files). Variables defined in these
files outside of any function have static duration (storage class) and
external linkage.

For sake of argument, let's say we have a program 'foo' which consists
of three translation units, foo.c, bar.c and baz.c plus a header, foo.h
which is #included in each of the .c files. Further assume there is a
single int object named x, defined in foo.c and accessable by functions
in foo.c, bar.c and baz.c as well. This way..

[foo.h]
extern int x;

[baz.c]
#include "foo.h"
void baz(void) {
x = 3;
}

[bar.c]
#include "foo.h"
void bar(void) {
x = 2;
}

[foo.c]
#include <stdio.h>
#include "foo.h"

int x = 1;

int main(void) {
printf("%d\n", x);
bar();
printf("%d\n", x);
baz();
printf("%d\n", x);
return 0;
}

I assume you know how to compile the three .c files and then create the
executable. That's technically Off Topic here. :-)

Each of foo.c, bar.c and baz.c include foo.h and so declare x an int
somewhere. Only foo.c defines 'int x = 1;' with external linkage. Now
bar and baz can 'see' x as if it were theirs.

There is no case for 'static int x = 1;'.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Jan 20 '06 #6
fox
> It's a declaration and a *tentative* definition.

That is clear, thanks.
Is it defined by C89 and supported by all C compilers (I don't care
about pre-ANSI ones) ?
Why can't you just move the declaration to the top of the file?
The real code is like this:

#include <xmms/plugin.h>

extern InputPlugin mod; // <-- I'll change it to static

static void init(void)
{
// ...
}

static int is_our_file(char *filename)
{
// ...
}

static void play_file(char *filename)
{
// ...
// (I use mod.output here)
}

static void pause(short paused)
{
mod.output->pause(paused);
}

static void stop(void)
{
// ....
}

static int get_time(void)
{
// ...
}

static InputPlugin mod = {
// ...
init,
NULL,
NULL,
is_our_file,
NULL,
play_file,
stop,
pause,
NULL,
NULL,
get_time,
// these are filled by XMMS at runtime (this includes the "output"
field):
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
};

// this is exported from the compiled *.so:
InputPlugin *get_iplugin_info(void)
{
return &mod;
}

Of course I could make forward declarations of my static functions,
for example:

static void pause(short paused);

(I'm sure this is a declaration and never a definition)
and then define "mod" at the top, but as you can see there are several
static functions while there's just one "mod".
For portability, you'll probably need to remove all references to 'static'.
Ehm, what?
'static' on variables is supposed to mean that it doesn't get exported to
the linker.
This is exactly what I want.
You seem to misunderstand the whole system.


No.

Thanks,
Piotr

Jan 20 '06 #7
Joe Wright wrote:
fo*@scene.pl wrote:
How do I (portably) make a forward reference to a static (I mean
file-scope) variable?

I've been using "extern" for years, for example:

extern int x;
int foo(void)
{
return x++;
}
static int x = 5;

... and gcc 3.4.4 and MSVC 2005 do not even warn that anything's wrong
here.

But gcc 4 gives me an error:

static declaration of 'x' follows non-static declaration

It seems that replacing "extern" with "static" makes it happy.

I always thought that "static" means a definition (and not merely a
declaration) for variables
and if you want to just declare a variable then you use "extern". Now I
cannot understand what "static int x;" actually is: just a declaration?
or declaration and definition?
Please note that I can remove the second "static int x" line and it
still compiles...

Can you explain me what C standards say about this issue and why some
compilers don't issue a warning while gcc 4 gives an error? Is it
because some compilers default to C89 and the other default to C9X ?

Thanks,
Piotr

You seem to misunderstand the whole system.


I didn't get this impression reading his post.

Assume a C program written in two or more translation units (.c files). Variables defined in these
files outside of any function have static duration (storage class) and
external linkage.

For sake of argument, let's say we have a program 'foo' which consists
of three translation units, foo.c, bar.c and baz.c plus a header, foo.h
which is #included in each of the .c files. Further assume there is a
single int object named x, defined in foo.c and accessable by functions
in foo.c, bar.c and baz.c as well. This way..

[foo.h]
extern int x;

[baz.c]
#include "foo.h"
void baz(void) {
x = 3;
}

[bar.c]
#include "foo.h"
void bar(void) {
x = 2;
}

[foo.c]
#include <stdio.h>
#include "foo.h"

int x = 1;

int main(void) {
printf("%d\n", x);
bar();
printf("%d\n", x);
baz();
printf("%d\n", x);
return 0;
}
If you compile this code with a C89 compiler you'll get undefined
behaviour. You did not provide a prototype for bar() and baz() so the
compiler will assume int. Since the actual return type is void, the
behaviour is undefined (IIRC). In C99 the code is not compilable since
a correct prototype in scope is needed.
I assume you know how to compile the three .c files and then create the
executable. That's technically Off Topic here. :-)

Each of foo.c, bar.c and baz.c include foo.h and so declare x an int
somewhere. Only foo.c defines 'int x = 1;' with external linkage. Now
bar and baz can 'see' x as if it were theirs.

There is no case for 'static int x = 1;'.


How would you declare a variable with static duration, file scope and
internal linkage if it was not in this way?

Jan 20 '06 #8
fo*@scene.pl wrote:
Of course I could make forward declarations of my static functions,
for example:

static void pause(short paused);
Why wouldn't you?
Too much typing?
(I'm sure this is a declaration and never a definition)
and then define "mod" at the top, but as you can see there are several
static functions while there's just one "mod".


--
pete
Jan 20 '06 #9
pete wrote:
fo*@scene.pl wrote:
Of course I could make forward declarations of my static functions,
for example:

static void pause(short paused);


Why wouldn't you?
Too much typing?

Some people just prefer to define the functions in the order they'll be
used. With statics, there's no need for declarations for other
translation units.

I always find it easier to just put prototypes in, that way if the
design changes I don't end up moving functions around to get them in
the correct order.
Brian

Jan 20 '06 #10
Default User wrote:

pete wrote:
fo*@scene.pl wrote:
Of course I could make forward declarations
of my static functions,
for example:

static void pause(short paused);


Why wouldn't you?
Too much typing?


Some people just prefer to define the functions
in the order they'll be
used. With statics, there's no need for declarations for other
translation units.

I always find it easier to just put prototypes in, that way if the
design changes I don't end up moving functions around to get them in
the correct order.


Me too.

--
pete
Jan 21 '06 #11
fox
> > Of course I could make forward declarations of my static functions,
for example:

static void pause(short paused);


Why wouldn't you?
Too much typing?


Yes. The problem is not one-time copy-paste work,
but that there would be two places to update in the future for each
function.
AFAIK, no compiler tells you when the argument names
in declarations/definition do not match.
If possible, I always avoid forward declarations (especially of
functions) in *.c file.

I have seen that some people prefer declaring all functions at the top,
but first it's easy to forget about declaring some functions, second
you
should probably declare all top-level variables too (for consistency).

The order of functions doesn't matter in the case of my XMMS plugin,
because they don't call each other.

I am still waiting for confirmation that tentative definitions of
statics
are guaranteed by C89.

Piotr

Jan 21 '06 #12
fo*@scene.pl wrote [quoting me]:
It's a declaration and a *tentative* definition.


That is clear, thanks.
Is it defined by C89 and supported by all C compilers (I don't care
about pre-ANSI ones) ?


Yes. Prior to C89, there was no portable way to forward reference
static variables.

-Larry Jones

I'm so disappointed. -- Calvin
Jan 21 '06 #13

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

Similar topics

3
by: mjm | last post by:
Folks, Please help me with the following problems: ******************************************** 1. I have a class template template<class Base> class Matrix : public Base { /* .... */ }
5
by: John Gabriele | last post by:
I'm hoping someone can please help me remember the C++ rule: When you're writing a header file for a class (say, some_namespace::Bar), and that class makes use of another class...
11
by: aleko | last post by:
This applies equally to function prototypes. Why do we have to tell the compiler twice? Other modern compiled languages don't have this requirement. Just curious, Aleko
2
by: John Ratliff | last post by:
I'm having issues with forward declarations and possibly member variables. Can you declare a member variable and pass it parameters. class x { private: y obj(this); } Is that valid? I'm...
134
by: James A. Donald | last post by:
I am contemplating getting into Python, which is used by engineers I admire - google and Bram Cohen, but was horrified to read "no variable or argument declarations are necessary." Surely that...
9
by: AnandRaj | last post by:
Hi guys, I have a few doubts in C. 1. Why static declartions are not allowed inside structs? eg struct a { static int i; }; Throws an error ..
1
by: Steve | last post by:
Can anyone explain why C++ .NET compiler throws error for the following code segment: // Forward declaration of ListViewItemComparer class public __gc class ListViewItemComparer ; public __gc...
26
by: samjnaa | last post by:
Hello. Please tell me whether this feature request is sane (and not done before) for python so it can be posted to the python-dev mailing list. I should say first that I am not a professional...
11
by: Jef Driesen | last post by:
I have the following problem in a C project (but that also needs to compile with a C++ compiler). I'm using a virtual function table, that looks like this in the header file: typedef struct...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...

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.