namespaces from header files in c++ -
i have created noname namespace variables inside in header, want initialize them in .cpp , see in main.cpp. noname namespace expecting work fine without mentioning namespace in .cpp. error if in .cpp had totally new , b. has idea how resolve it?
xx.h
namespace { int a; int b; }
.cpp
#include "xx.h" = 5; b = 10;
main.cpp
#include <iostream> #include "xx.h" int main() { std::cout << "values" << << b << std::endl; }
you may not use assignment statements outside functions. may declare or/and define objects . valid code be
namespace { int = 5; int b = 10; }
main.cpp
#include <iostream> #include "xx.h" int main() { std::cout << "values" << << b << std::endl; }
take account objects declared in unnamed namespaces have internal linkage. means if header included in more 1 module in each module declares separate namespace.
consder following example
unnamed.h
namespace { int = 5; int b = 10; } void f();
second.cpp
#include <iostream> #include "unnamed.h" void f() { = 10; b = 5; std::cout << "a = " << << ", b = " << b << std::endl; }
main.cpp #include #include "unnamed.h"
int main() { f(); std::cout << "a = " << << ", b = " << b << std::endl; return 0; }
the output is
a = 10, b = 5 = 5, b = 10
Comments
Post a Comment