473,624 Members | 2,557 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 12153


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.goo glegroups.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*******@bitb ucket.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_Keit h) 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(cha r *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_in fo(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

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

Similar topics

3
5460
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
1872
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 (some_namespace::Foo), -------------------------------- snip -------------------------------- #ifndef GUARD_Foo_HPP #define GUARD_Foo_HPP namespace some_namespace {
11
2426
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
2293
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 getting a lot of problems, but it may not be due to
134
7854
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 means that if I misspell a variable name, my program will mysteriously fail to work with no error message. If you don't declare variables, you can inadvertently re-use an variable used in an enclosing context when you don't intend to, or
9
2817
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
2317
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 class CProgramLoaderForm : public System::Windows::Forms::Form { ListViewItemComparer* m_ListViewItemComparer ;
26
2535
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 programmer with too much technical knowledge. I would like to have something like the "option explicit" statement in Visual Basic which turns on C-like checking for declaration of variables. This is highly helpful for people who are coming from C/C+...
11
8309
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 device_t { const device_backend_t *backend; ... } device_t; typedef struct device_backend_t {
0
8249
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
8179
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
8685
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
8633
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
8348
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
8493
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...
1
2613
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
1797
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1493
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.