why is "static" both storage class and linkage specifier? - c++

The static keyword defines how a variable is to be stored in memory, i.e., in the data segment if initialized or in the BSS if uninitialized. But the keyword also specifies how a variable is to be linked, i.e., local scope only.
How or why are these two things related? Can the two be separated, or was this a necessary design consideration?
IOW, why is it that if I want my variable to exist for the duration of the program, it must be linked internally?

The keyword static can probably be seen as somewhat "overloaded".
The following usage-options are all viable:
Static local variables
Static global variables
Static member variables
Static global functions
Static member functions
Variables:
In terms of runtime, all types of static variables are essentially the same. They all reside in the data-section of the program, and their addresses remain constant throughout the execution of the program. So the only difference between them is during compilation, in the scope of declaration:
Static local variable: recognized by the compiler only in the scope of the function
Static global variable: recognized by the compiler only in the scope of the file
Static member variable: recognized by the compiler only in the scope of the class
Functions:
In terms of runtime, all types of functions (static and non-static) are essentially the same. They all reside in the code-section of the program, and their addresses remain constant throughout the execution of the program. So the only difference between them is during compilation, in the scope of declaration:
Static global function: recognized by the compiler only in the scope of the file
Static member function: recognized by the compiler only in the scope of the class

Re
“why is it that if I want my variable to exist for the duration of the program, it must be linked internally?”
no that is not so.
Program-global variables are supported, and that's the default for a non-const namespace level variable. It's just wise to avoid them (to the extent possible).
Re apparent conflation of concepts in the single keyword static, since C++ doesn't support dynamic libraries, local to the translation unit linkage is not meaningful for lifetime shorter than the program execution.

Related

Is there any sense to declare static global variable as inline?

Consider, global variable (not static class member!) is declared in the header file:
inline static int i{};
It is valid construction for several compilers that I tested, and experiments demonstrate that several distinct objects will be created in different translation units, although it is also declared as inline (it means that only one instance of that variable must exist in the program). So, has static keyword more priority than inline in that case?
So, has static keyword more priority than inline in that case?
Pretty much. static has an effect that interferes with inline. The C++ standard states that
... An inline function or variable with external linkage shall have
the same address in all translation units.
And the static qualifier imposes internal linkage, so the single address guarantee does not have to hold. Now, a name with internal linkage in different translation units is meant to denote different object in each TU, so getting multiple distinct i's is intended.
All in all, the static negates the inline. And there is no point to having a static inline variable over a plain static one.

CreateTimerQueueTimer termination on WM_CLOSE [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I know the keyword in c has two usage:
modify variables
modify global variables
this usage limited the scope of global variable range from the point that defined to the end of the file.
modify local variables
this usage limited the scope of local variable in the function that defined, but also remained in the static area of memory
modify functions
this means can only invoke the function in the file it's defined.
and in c++, beside the usage in c, static also used to modify the data member and function member of class. This usage limited the member belong to the class instead of the objects of the class.
I want to know are there anything else usage of static in c/c++?
static is probably the most confusingly overloaded keyword in both C and C++. It means different things in different places.
Within functions, static is a storage class, denoting variables which exist for the lifetime of the programme. So saying
void f() {
static int i = 0;
}
says that the value of i will be preserved between calls to f(). Other storage classes are the default auto (but beware the change in meaning in C++11), extern, and register, plus thread_local in C11/C++11.
At file scope (or namespace scope in C++), static is a linkage specifier. Functions and variables marked static in this way have internal linkage, and so are local to the current translation unit. What this means is that a function like
static int f() {
return 3;
}
can only be referenced by other functions inside the same .c file. This usage of static was deprecated in C++03 in favour of unnamed namespaces. I read somewhere it was undeprecated again in C++11.
In C++, when applied to a member function or member variable of a class, it means that the function or variable does not need a class instance in order to be accessed. There is little different between "class static" member functions/variables and global functions/variable in terms of implementation, except that C++ class access specifiers apply to members.
One last one: in C99 (but not C++), static can be used within an array function parameter, like so:
void f(int a[static 4]) {
}
this specifies that the parameter a must by an integer array of size at least 4.
I think that's all of them, but let me know in the comments if there are any I've forgotten!
Static In the C language family, a static variable is one that exists for the lifetime of a compilation
unit (a source file or module). A static variable can be declared module-wide, and thus be
accessed by all functions defined within the same source file. Such a static variable cannot
be directly accessed from other modules, but inner-module API can pass pointers to static variables and
modify those through pointers. A static variable can also be declared within a function body, where the
usual scope rules apply. A static variable declared within a function is only initialized when
the module is initialized (typically when the application loads), and preserves its values over multiple
invocations of the function that contains the definition.
In C++, a static variable can also be a member of a class definition. Access to a static member
variable is governed by the standard access modifiers (private, public, protected), but all instances of
this class share the same static variable, and share the same value. Modifying the value of this variable
affects all objects of the class. VolatileThe volatile keyword is something all together different, and not in any way
an opposite to static. A static variable may or may not be declared volatile, just as a global or local variable
can be. The volatile keyword is a hint informing the compiler that the variable's value
might change without the compiler's knowledge. Therefore, the compiler's code optimizer cannot make assumptions
about the variable's current value, and must always (re-) read the variable's content.
In reference to c++ -> The static keyword can be used to declare variables, functions, class data members and class functions.
Here are the common usages in different scenarios ( ref from MSDN )
When you declare a variable or function at file scope (global and/or namespace scope), the static keyword specifies that the variable or function has internal linkage. When you declare a variable, the variable has static duration and the compiler initializes it to 0 unless you specify another value.
When you declare a variable in a function, the static keyword specifies that the variable retains its state between calls to that function.
When you declare a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. A static data member must be defined at file scope. An integral data member that you declare as const static can have an initializer.
When you declare a member function in a class declaration, the static keyword specifies that the function is shared by all instances of the class. A static member function cannot access an instance member because the function does not have an implicit this pointer. To access an instance member, declare the function with a parameter that is an instance pointer or reference.
You cannot declare the members of a union as static. However, a globally declared anonymous union must be explicitly declared static.
check following also:
The static keyword and its various uses in C++
static keyword usage

Static vs New/Malloc

I was wondering if people could shed some light on the uses of "static." I have never run into an issue where I have explicitly declared a variable or method as static. I understand that when declaring something as "static" it gets stuffed into the data segment of your program, similar to globals, and hence the variable is accessible for the run of your program. If this is the case, why not just make a static variable a global variable. Hell, why not just throw this variable on the heap using a new or a malloc, both methods ensure the variable will be available for you throughout the run of your program.
static has multiple meanings in C, and C++ heaps on even more.
In a file scope declaration (what I think the question is about), static controls the visibility of an identifier.
Let's set aside C++ and use the C concepts.
File scope identifiers which name objects or functions have linkage. Linkage can be external (program-wide) or internal (within one translation unit).
static specifies internal linkage.
This is important because if a name with internal linkage appears in multiple units, those occurrences are not related. One module can have a static foo function and another one in the same program can have a different foo function. They both exist and are reachable by the name foo from their respective units.
This is not possible with external linkage: there must be one foo.
malloc creates an object which is potentially available everywhere in a program, as long as it is not freed, but in a different sense. The object is available if you have its pointer. A pointer is a kind of "run time name": an access key to get to the object. Linkage makes an object or function available if you know its name (at compile time) and if that object and function has the right kind of linkage relative to where you're trying to access it from.
In a dynamic operating system in which multiple programs come into life and terminate, the storage for its static data and functions (whether they have external or internal linkage) is in fact dynamically allocated. The system routine which loads a program has to do something similar to malloc to fetch memory for all of the fixed areas of the program.
Sometimes C programs use malloc even for "singleton" objects that are referenced globally via global pointers. These objects behave like de-facto static variables since they basically have a lifetime which is almost that of the entire program, and are accessed through the pointer, which is accessed by name. This is useful if the objects have properties (such as size) that is not known until run time, or if their initialization is expensive and they are not always needed (only when certain cases occur in the program).
Supplemental factoids about static and extern:
In C, at file scope, extern ensures that the declaration of an object, where an initializer is omitted, is in fact a declaration. Without extern it is a tentative definition, but if an initializer is present, then it is a definition.
In C, at file scope extern doesn't mean "this declaration has external linkage", surprisingly. An extern declaration inherits linkage from a previous declaration of the same name.
A block-scope extern in C means "this name, which is being introduced into this scope, refers to the external definition with external linkage". The linkage is inherited from a previous file-scope declaration of the name, if it exists, otherwise it is external.
A block-scope static on an object controls not linkage, but storage duration. A static object is not instantiated each time on entry into the block; a single copy of it exists, and can be initialized prior to program startup. (In C++, non-constant expressions can initialize such object or its members; in that case, initialization occurs on the first execution of the block).
A block-scope static function declaration declares a function with internal linkage.
There is no way, in a block scope, to declare an external object name which has internal linkage. Paradoxically, the first extern declaration in the following snippet is correct, but the second, block-scope one, is erroneous!
static int name; /* external name with internal linkage */
extern int name; /* redundant redeclaration of the above */
void foo(void)
{
int name; /* local variable shadowing external one */
{
/* attempt to "punch through" shadow and reach external: */
extern int name; /* ERROR! */
}
}
Clearly, the word "external" has an ambiguous meaning between "outside of any function" and "program-wide linkage" and this ambiguity is embroiled in the extern keyword.
In C++, static takes on additional meanings. In a class declaration, it declares "static member functions" which belong to the class scope and have the same access to class instances as non-static member functions do, but are not invoked on objects (do not have the implicit this parameter). Class data members marked static have a single class-wide instance; they are not instantiated per-object. (Unfortunately, they don't participate properly in inheritance like true object-oriented class variables, which can be overridden in a derived class to be instance or vice versa.)
In C++, a privacy similar to internal linkage can be achieved using an unnamed namespace rather than static. Namespaces make the internal/external linkage concept mostly an obsolete mechanism for C compatibility.
C++ involves extern in the special extern "LANG" syntax (e.g. extern "C").
static_cast is unrelated to static; what they have in common is "static" meaning "prior to program run time": static storage is determined prior to run time, and the conversion of a static casts is also determined at compile time (without run-time-type info).

what's the difference meaning of the keyword static between c and c++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I know the keyword in c has two usage:
modify variables
modify global variables
this usage limited the scope of global variable range from the point that defined to the end of the file.
modify local variables
this usage limited the scope of local variable in the function that defined, but also remained in the static area of memory
modify functions
this means can only invoke the function in the file it's defined.
and in c++, beside the usage in c, static also used to modify the data member and function member of class. This usage limited the member belong to the class instead of the objects of the class.
I want to know are there anything else usage of static in c/c++?
static is probably the most confusingly overloaded keyword in both C and C++. It means different things in different places.
Within functions, static is a storage class, denoting variables which exist for the lifetime of the programme. So saying
void f() {
static int i = 0;
}
says that the value of i will be preserved between calls to f(). Other storage classes are the default auto (but beware the change in meaning in C++11), extern, and register, plus thread_local in C11/C++11.
At file scope (or namespace scope in C++), static is a linkage specifier. Functions and variables marked static in this way have internal linkage, and so are local to the current translation unit. What this means is that a function like
static int f() {
return 3;
}
can only be referenced by other functions inside the same .c file. This usage of static was deprecated in C++03 in favour of unnamed namespaces. I read somewhere it was undeprecated again in C++11.
In C++, when applied to a member function or member variable of a class, it means that the function or variable does not need a class instance in order to be accessed. There is little different between "class static" member functions/variables and global functions/variable in terms of implementation, except that C++ class access specifiers apply to members.
One last one: in C99 (but not C++), static can be used within an array function parameter, like so:
void f(int a[static 4]) {
}
this specifies that the parameter a must by an integer array of size at least 4.
I think that's all of them, but let me know in the comments if there are any I've forgotten!
Static In the C language family, a static variable is one that exists for the lifetime of a compilation
unit (a source file or module). A static variable can be declared module-wide, and thus be
accessed by all functions defined within the same source file. Such a static variable cannot
be directly accessed from other modules, but inner-module API can pass pointers to static variables and
modify those through pointers. A static variable can also be declared within a function body, where the
usual scope rules apply. A static variable declared within a function is only initialized when
the module is initialized (typically when the application loads), and preserves its values over multiple
invocations of the function that contains the definition.
In C++, a static variable can also be a member of a class definition. Access to a static member
variable is governed by the standard access modifiers (private, public, protected), but all instances of
this class share the same static variable, and share the same value. Modifying the value of this variable
affects all objects of the class. VolatileThe volatile keyword is something all together different, and not in any way
an opposite to static. A static variable may or may not be declared volatile, just as a global or local variable
can be. The volatile keyword is a hint informing the compiler that the variable's value
might change without the compiler's knowledge. Therefore, the compiler's code optimizer cannot make assumptions
about the variable's current value, and must always (re-) read the variable's content.
In reference to c++ -> The static keyword can be used to declare variables, functions, class data members and class functions.
Here are the common usages in different scenarios ( ref from MSDN )
When you declare a variable or function at file scope (global and/or namespace scope), the static keyword specifies that the variable or function has internal linkage. When you declare a variable, the variable has static duration and the compiler initializes it to 0 unless you specify another value.
When you declare a variable in a function, the static keyword specifies that the variable retains its state between calls to that function.
When you declare a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. A static data member must be defined at file scope. An integral data member that you declare as const static can have an initializer.
When you declare a member function in a class declaration, the static keyword specifies that the function is shared by all instances of the class. A static member function cannot access an instance member because the function does not have an implicit this pointer. To access an instance member, declare the function with a parameter that is an instance pointer or reference.
You cannot declare the members of a union as static. However, a globally declared anonymous union must be explicitly declared static.
check following also:
The static keyword and its various uses in C++
static keyword usage

What is default storage class for global variables?

What is default storage class of a global variable?
While searching on web I found, some sites say it is static. But, static means internal linkage and the variable can not be available outside the file scope i.e it should not be available to other object files. But, they still can be accessed to other files using declarations like extern int i.
And, if I explicitly mention static to global variable then it is not available outside the file scope.
Then, what is correct default storage class for the global variables?
The default storage duration is static, but default linkage is external. You're not the only one to find it a bit confusing. The C Book (always a good reference) says:
"You'll probably find the interactions
between these various elements to be
both complex and confusing: that's
because they are!"
The section with that quote, Declarations, Definitions and Accessibility, has a helpful table (8.1). The last row describes the case you're interested in. As it notes, data objects with no storage class specifier have external linkage and static duration.
There's no "default storage class" for what is commonly known as "global" variables. When a variable is defined in namespace scope it always has static storage duration. There's no way to change that, which is why the idea of something "default" is not applicable here. (And storage duration is what it is correctly called.)
When you apply the keyword static to a variable defined in namespace scope it does not affect its storage duration - it was static already and it remains static - but it affects it linkage. The keyword static changes the linkage of such variable from external (default) to internal. Linkage is a separate concept, virtually unrelated to storage duration.