Function/Variable Scope   «Prev 

Using anonymous namespaces - Exercise

Objective: Re-code a multifile program that uses static external declarations so it uses anonymous namespaces instead.

Namespace support

You will only be able to complete this exercise if your compiler supports namespaces.

The program

Here is a program that consists of two files and uses the static storage class. This code is also available in two files named prog1.cpp and prog2.cpp, which can be found in the compressed course download file available on the Resources page.

//file prog1.cpp
static int  foo(int i)
   return (i * 3);

int  goo(int i)
   return (i * foo(i));

//file prog2.cpp
#include  <iostream.h>

int foo(int i)
   return (i * 5);

int  goo(int i);  // imported from file prog1.cpp
int main()
   cout << "foo(5) = " << foo(5) << endl;
   cout << "goo(5) = " << goo(5) << endl;

Functions at file scope are by default extern.
The foo() in file prog1.cpp is private to that file, but goo() is not. Thus, redefining foo() in file prog2.cpp does not cause an error.

Play around with the files

Before you attempt to rewrite this program using anonymous namespaces, try to predict what the current program will print.
Now try dropping static from foo() and see what error your compiler gives. Next, try making goo() inline in prog1.cpp and see what error message your compiler gives.

Rewrite the program

Rewrite the program using an anonymous namespace in place of the static external declaration.
Remember, this is a multifile program. Keep prog1.cpp and prog2.cpp as separate files. Paste the source code of your program below and click the Submit button when you are ready to submit this exercise.