简体   繁体   中英

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++
}

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.

将带有extern声明的命名空间放在头文件中,并将该头文件包含在需要该变量的所有源文件中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM