How to work with variable in namespace - c++

I think I hvae a fundamental misunderstanding of namespace and/or static variable. But I have tried this test code (typed by hand, forgive typos)
test.h:
namespace test{
static int testNum=5;
void setNum(int value);
}
main.cpp:
#include <test.h>
int test::setNum(int value){
testNum=value;
}
int main(){
test::setNum(9);
cout<<test::testNum;
}
when I run this I get the value 5, not 9 as I would have expected. It seems almost as if I have two instances of the testNum variable, but that seems to be the exact opposite of what static should be doing. I'm guessing I've made a mistake in assuming that these features were identical to their java equvilants somehow...
I also get an error stating that testNum is declared multuple times if I remove the static from my declaration of testNum, could someone explain why that is the case as well?
Thank you

First, your misunderstanding has nothing to do with namespaces, it's only about static. For the rest of this answer I'm going to refer to simply testNum because the fact it's in a namespace is irrelevant.
I'm also assuming you have another file, probably called test.cpp, which also includes test.h and defines the setNum function.
When a variable or function at namespace-scope (i.e. not a class member or local to a function) is declared static it means the entity's name is internal to that file. Formally it has "internal linkage", meaning it can't be referred to by name or linked to from other files (it can be indirectly referred to through a pointer or by passing it as an argument to another function.) That means if several files define static int testNum then each file has its own internal variable with that name, distinct from the testNum in every other file (in fact one file could have static int testnum and another could have static double testnum and another static char* testNum, they'd all be distinct and internal to each file.) If you put a definition like that in header then every file that includes the header has its own testNum.
So with static on your variable in a header you have a different variable called testNum in every file that includes test.h. That means if you set testNum in one file and call a function in a different file which uses testNum it refers to a different variable, which just happens to have the same name.
Because of this, declaring non-const static variables in headers is almost always wrong.
Without static you would have a definition of the testNum variable in every file that includes test.h, which is not allowed: every entity must be defined once and once only in your program. The way to solve that is to declare the variable in the header, but not define it, which you do by telling the compiler the variable is extern:
extern int testNum; // N.B. no "= 1" here
That tells the compiler there is a variable with "external linkage" called testNum, so when code refers to testNum it will always mean the same variable (not some name with internal linakge that is a different entity in every file.) After declaring an extern variable it is your responsibility to ensure there is exactly one definition provided somewhere in the program, so in exactly one file (i.e. not in a header that gets included in multiple files) you define it:
int testNum = 1;

static at namespace scope is a misnomer, and shouldn't be used. It
means simply that the entity declared static has internal name binding;
in other words, that the same name in other translation units will refer
to a different entity, and in the case of variable definitions, that
there will be a separate instance of the variable in each translation
unit. It has no effect on lifetime. (All variables declared or
defined at namespace scope have static lifetime.)
static at namespace scope is also deprecated. Don't use it.
With regards to declaring a variable in a header: prefix it with
extern, and not static. If a variable is declared extern, and
there is no initialization, the declaration is not a definition. Of
course, in this case, you must provide a definition somewhere (in a
single source file). Something along the lines of:
extern int testNum = 5;
int testNum = 5;
int testNum; // implicitly initialized with 0.
EDIT:
To clarify somewhat: there is some confusion here between lifetime and
name binding:
an object has a lifetime (auto, static or dynamic—or temporary, or exception), and
a name is bound to an entity; if the name is declared to be a variable, the entity is an object.
Do not confuse the keyword static with static lifetime. (Functions
can be static, but functions have no defined lifetime in C++; they're
just there.)
The rules regarding these are not very orthognal. Basically, with
regards to lifetime:
all variables declared at namespace scope have static lifetime, always,
variables declared at local scope have auto lifetime unless they are declared static, and
variables declared at class scope have the lifetime of the class object which contains them, unless they are declared static.
regards to lifetime.
Objects with static lifetime come into being sometime before main, and
live until after you return from main.
With regards to name binding:
variables declared at namespace scope have external name binding,
unless they are declared static, in which case they have internal
name binding (but this use of static is deprecated), or if they are
const, and are not declared extern,
variables declared at class scope have external name binding, even if they are declared static, and
variables declared at block scope have no binding.
Finally, there is the question of whether a declaration is a definition
or not. If it is a definition, memory is allocated and the object is
(or may be) initialized. If it is not a definition, it simply tells the
compiler that there is a definition somewhere else for the entity
(object) declared in the declaration. In general, a variable
declaration is a definition unless it is declared extern and does
not have an initializer.

You might want to make sure your code actually has problems before you post it asking what's wrong ;)
I copy/pasted and fixed your typos, and manually did the include:
#include <iostream>
using namespace std;
namespace test{
static int testNum=5;
void setNum(int value);
}
void test::setNum(int value){
testNum=value;
}
int main(){
test::setNum(9);
cout<<test::testNum;
}
result:
$ ./a.out
9
What you haven't said is what else is in your program. If you have more than just main.cpp, and include your test.h, then each .cpp file will have its own copy of testNum. If you want them to share then you need all but one to mark it as extern.

Related

why static variable in a class gives a linking error?

Why static variable in a class has to be re-initialised as a global in the file?
Otherwise, it gives a linking error. What is the theory behind it? I understand that the static variable will be in the Data Segment.
my_class.h
class my_class
{
public:
static int m_fid;
void get_fid();
};
my_class.cpp:
#include <iostream>
using namespace std;
int main()
{
my_class t;
/**this gives a linking error */
my_class::m_fid = 0;
return 0;
}
First of all the definition of static variable is wrong.
Instead of my_class::m_fid = 0; you should define as int my_class::m_fid = 0; when you do that there will be no more linker error..
Another thing as per standard...
The definition for a static data member shall appear in a namespace
scope enclosing the member’s class definition.
Yes, static variables (wherever they are declared) go into the data segment.
static means different things depending where it's used, though.
At file or namespace scope, it means the variable is specific to the .cpp file (translation unit).
At local scope, it means the variable is specific to that scope, which may be specific to the translation unit, or shared between translation units if it's in an inline function.
At class scope, a static member declaration inside the class is effectively (almost) the same as one outside the class with the extern specifier.
Like a variable declared extern, a static member is only considered to be declared (and not defined) until a definition is reached.
There is an exception for some static const and static constexpr members, that they may be initialized inside the class and then immediately used, subject to the restriction that the address of the member is never used.

Difference between File Scope and Global Scope

I am a student and I am confused about global and file scope variables in C and C++.
Is there any difference in both perspectives? If yes, please explain in detail.
A variable with file scope can be accessed by any function or block within a single file. To declare a file scoped variable, simply declare a variable outside of a block (same as a global variable) but use the static keyword.
static int nValue; // file scoped variable
float fValue; // global variable
int main()
{
double dValue; // local variable
}
File scoped variables act exactly like global variables, except their use is restricted to the file in which they are declared.
It is perhaps clearer to illustrate file (or more precisely, translation unit)-scope vs global scope when there are actually multiple translation units...
Take 2 files (each being it's own translation unit, since they don't include each other)
other.cpp
float global_var = 1.0f;
static float static_var = 2.0f;
main.cpp
#include <cstdio>
extern float global_var;
//extern float static_var; // compilation error - undefined reference to 'static_var'
int main(int argc, char** argv)
{
printf("%f\n", global_var);
}
Hence the difference is clear.
A name has file scope if the identifier's declaration appears outside of any block. A name with file scope and internal linkage is visible from the point where it is declared to the end of the translation unit.
Global scope or global namespace scope is the outermost namespace scope of a program, in which objects, functions, types and templates can be defined. A name has global namespace scope if the identifier's declaration appears outside of all blocks, namespaces, and classes.
Example:
static int nValue; // file scoped variable
float fValue; // global variable
int main()
{
double dValue; // local variable
}
Read more here.
File scope: Any name declared outside all blocks or classes has file scope. It is accessible anywhere in the translation unit after its declaration. Names with file scope that do not declare static objects are often called global names.
In C++, file scope is also known as namespace scope.
Read this carefully now.
You use those #include<'...'.h> statements at the top of your program/code.
What you actually are doing there is telling the computer to refer to the functions prewritten in those *h*eader files.That is, those functions have file scope.You donot write the code of printf scanf and functions like these cauz they are somewhere in header files.
Variables declared outside a function have "file scope," meaning they are visible within the file. Variables declared with file scope are visible between their declaration and the end of the compilation unit (.c file) and they implicitly have external linkage and are thus visible to not only the .c file or compilation unit containing their declarations but also to every other compilation unit that is linked to form the complete program.
Global variables can, as the name suggests, be considered to be accessible globally(everywhere)

How does extern work?

extern is a storage class in C. How exactly does it work? The output of the code given below is 20. How is this the output?
#include <stdio.h>
int main()
{
extern int a;
printf("%d", a);
return 0;
}
int a=20;
It means three things:
The variable has external linkage, and is accessible from anywhere in the program;
It has static storage duration, so its lifetime is that of the program (more or less); and
The declaration is just a declaration, not a definition. The variable must also be defined somewhere (either without the extern, or with an initialiser, or in your case, both).
Specifically, your extern int a; declares that the variable exists, but doesn't define it at that point. At this point, you can use it, and the linker will make sure your use refers to the definition. Then you have the required definition, int a=20; at the end, so all is well.
extern in this case indicates that the symbol a is defined in a different location, such as a different module. So the linker looks for a symbol with the same name in all of the modules that are linked, and if one exists then it sets the address to your local variable a with the address to the externally defined variable. Since you have another a defined outside of your main() function, the a inside your main() function is (basically) the same variable as the one outside.
Since the global a is initialized before the main function executes, the value is 20 by the time you access it.
extern means i declare a variable, just like you implement a function in a source file and declare the prototype in a header to allow other source file to use it.
If you put a global variable in a source file, and use a header to declare it with the extern keyword, each source file including the header will see the variable.
The linker will do the job to tie everything just as it does with functions
extern as a storage class specifier tells the compiler that the object being declared is not a new object, but has storage elsewhere, i.e., is defined elsewhere. You can try this experiment with your code to see how it works. Leave out the keyword extern in your declaration of int a in main(). Then your printf() will print some garbage value, as it would be a new definition of an int with the same identifier, which would hide the global a declared elsewhere.
You use extern to tell the compiler that the variable is defined elsewhere. Without extern in your program compiler would define another variable a (in addition to this in the global scope) in your main() function that would be printed uninitialized.

"extern" inside a function?

Well, reading "a bit old" book ("The C programming language", second edition, by Dennis Ritchie), I came a cross the following:
An external variable must be defined, exactly once, outside of any function; this sets aside storage for it. The variable must also be declared in each function that wants to access it
and I was like - what?!
"The variable must also be declared in each function that wants to access it". Then, I was shocked one more time:
int max;
/* ... */
int main()
{
extern int max;
/* ... */
}
And one more - what?!
As far as I know (obviously, it's not much and far from enough), extern makes sense only when you define a global variable somewhere and you want to access it through another file (not to define it again).
So:
What's the point of this extern int max inside the main or any other function?
Does the standard really says, that this is a must (that I need to declare, for this example, this max in each function, that will use it?)
Is this the same for C++ (that's why I placed the C++ tag)? This is the first time I see something like this.
Note: this is not the same as What is the use of declaring a static variable as extern inside a function?
Your post surprised me. I had no recollection of that and I've read K&R long ago. I only have the first edition here and it is there too. However, that is not all it says. From the first edition:
The variable must also be declared in each function that wants to
access it; this may be done either by an explicit extern declaration
or implicitly by context.
Note the "implicitly by context." Later in the text:
...if the external definition of a variable occurs in the source file
before its use in a particular function, then there is no need for an
extern declaration in the function. The extern declarations in main,
... are thus redundant. In fact, common practice is to place
definitions of all external variables at the beginning of the source
file, and then omit all extern declarations.
So this is saying that making the extern variable visible can be done inside the function for just that function, or can be done outside any function for all functions following it in the source file. I believe that this is the only place in the book where it is done inside the function, later it uses the familiar once for the file approach.
extern int max inside main or function is saying to the compiler "I am not a local variable inside the main or function, I am the global variable defined elsewhere".
If the global is declared in the same file, not useful. In different file,yes, but not in each function, just declare one time in the head file of the source that use this global variable. This is the same in c++.
The extern is linkage. It means this name, max, is linked to other occurrences of the name, possibly in other files. (That is, when the object modules are linked together to make an executable, all the linked references to this name will be made to refer to the same object.)
The scope of this declaration is the remainder of the function body it is in. That means other functions in this file do not see the name declared by this declaration (unless they declare it themselves).
Scope and linkage are different things.
Another possible reason for extern inside a function is to make sure that no local variable is shadowing the global variable
Without extern:
int max = 33;
int main()
{
int max;
printf("%d", max); // prints indeterminate value (garbage)
}
With extern
int main()
{
extern int max;
int max;
printf("%d", max);
}
Output:
error: redeclaration of ‘max’ with no linkage

Use of static variables and functions in global scope

Is there a use for flagging a variable as static, when it lies in the global scope of a .cpp file, not in a function?
Can you use the static keyword for functions as well? If yes, what is their use?
Yes, if you want to declare file-scope variable, then static keyword is necessary. static variables declared in one translation unit cannot be referred to from another translation unit.
By the way, use of static keyword is deprecated in C++03.
The section $7.3.1.1/2 from the C++ Standard (2003) reads,
The use of the static keyword is
deprecated when declaring objects in a
namespace scope; the
unnamed-namespace provides a superior
alternative.
C++ prefers unnamed namespace over static keyword. See this topic:
Superiority of unnamed namespace over static?
In this case, keyword static means the function or variable can only be used by code in the same cpp file. The associated symbol will not be exported and won't be usable by other modules.
This is good practice to avoid name clashing in big software when you know your global functions or variables are not needed in other modules.
Taking as an example -
// At global scope
int globalVar; // Equivalent to static int globalVar;
// They share the same scope
// Static variables are guaranteed to be initialized to zero even though
// you don't explicitly initialize them.
// At function/local scope
void foo()
{
static int staticVar ; // staticVar retains it's value during various function
// function calls to foo();
}
They both cease to exist only when the program terminates/exits.