The following code works correctly:
file1.cpp
//global variable
int g_myvar1 = 5;
file2.cpp
int myfunc()
{
extern int g_myvar1;
g_myvar1++
}
How can I do file2.cpp if file1.cpp is as follows:
file1.cpp
namespace myns
{
//global variable
int g_myvar1 = 5;
}
NOTE1, the following gives compilation error on GCC 4.7 "invalid use of qualified-name". I tried 'using namespace' with no luck also.
int myfunc()
{
extern int myns::g_myvar1;
g_myvar1++
}
NOTE2, The following works, but I am looking for only-local variable definition.
namespace myns
{
//global variable
extern int g_myvar1;
}
int myfunc()
{
myns::g_myvar1++
}
Access global variable using 'extern'. By declaring a variable as extern we are able to access the value of global variables in c language. Basically, extern is a keyword in C language that tells to the compiler that definition of a particular variable is exists elsewhere. Here I am declaring x as extern and then the print the value of x.
It is the variable that is visible from all other scopes. We can access global variable if there is a local variable with same name in C and C++ through Extern and Scope resolution operator respectively. 1) We can access a global variable if we have a local variable with same name in C using extern.
Here, x is one local variable (scope), and it's only visible within this block. extern dictates the storage, meaning this is merely one declaration, this variable is defined somewhere else. Would recommend the C standard for definite reference.
Can you extern a namespace scope variable? I have been using C++ lately rather than C. In C we have no namespaces so defining a global variable in one translation unit and declaring it as extern in another is fine. I know I can also do that in C++ but what I am trying to do instead is to have a namespace scoped variable extern'ed.
Use using
:
void f()
{
using myns::g_myvar1;
++g_myvar1;
}
You've declare the variables (with extern
keyword) in .h
file in a namespace myns
, and define them in .cpp
file. And include the header file wherever you want to use the variables.
Put the namespace with the extern
declaration in a header file, and include that header file in all source files needing that variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With