extern local variable for global variable inside namespace
Solution 1
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.
Solution 2
Put the namespace with the extern
declaration in a header file, and include that header file in all source files needing that variable.
Yousf
Embedded software engineer with more than four years of experience in designing/developing/testing cutting-edge embedded software. I do web-development for fun.
Updated on June 24, 2022Comments
-
Yousf almost 2 years
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++ }
-
Yousf over 11 yearsI know this is the best solution, but I was looking for a solution which don't need this include.
-
Yousf over 11 years+1 for the new usage of using keyword. But this still needs declaration of "namespace mynm{extern int g_myvar1;}" before void f()
-
Nawaz over 11 years@Yousf: Yes, it is better to declare them in
.h
file, and define them in.cpp
file. -
Some programmer dude over 11 years@Yousf In C and C++ things have to be declared before they are used, it's as simple as that. If you don't have some kind of declaration of the namespace or the data inside it, the compiler will not know of those identifier names.
-
Ant almost 4 years@Yousf Thank you. It took me a long time to find that syntax. With your suggestion you don't need the using.