Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern local variable for global variable inside namespace

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++
}
like image 506
Yousf Avatar asked Jan 14 '13 12:01

Yousf


People also ask

How to access global variable using 'extern' in C language?

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.

What is global variable in C++?

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.

What is the difference between local variable and extern variable?

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?

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.


2 Answers

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.

like image 95
Nawaz Avatar answered Oct 08 '22 20:10

Nawaz


Put the namespace with the extern declaration in a header file, and include that header file in all source files needing that variable.

like image 32
Some programmer dude Avatar answered Oct 08 '22 21:10

Some programmer dude