Function/Variable Scope   «Prev  Next»
Lesson 11 Anonymous namespaces
Objective Multifile Program uses Anonymous Namespaces

C++ Multifile Program uses Anonymous Namespaces

Rewrite a multifile program so it uses anonymous namespaces in place of static external declarations. You can use anonymous, or unnamed, namespaces to provide a unique scope similar in effect to the use of static external declarations.
For example, in the following code fragment, the function goo() is declared as static:

static int goo(int a)
{
   // code for function goo
}

int foo(int a){
   //goo() is available here
   //but not in other files
   b = goo(a);
}

You could use an anonymous namespace to accomplish the same thing:
namespace {  //anonymous namespace
 int goo(int a){
   //goo function code
 }
 int foo(int a){
   // start foo code 
   //goo() is available here
   //but not outside this namespace
   b = goo(a);
   // end foo code 
 }
}  //end namespace

Aonymous Namespaces - Exercise

Click the Exercise link below to rewrite a multifile program using static external declarations so it uses anonymous namespaces instead. You will not be able to do this exercise unless your compiler supports anonymous namespaces.
Aonymous Namespaces - Exercise