Namespaces and Symbol Conflicts
Let’s say that we’re engaged in a bit of recreational code porting. An example might be porting code from one operating system to another or incorporating code from an old library into a new code base. Figure 1 illustrates the process.
Figure 1 Porting code from one location to another
Let’s assume that we really need and want the code that’s being ported, but we don’t know it all that well. Further, let’s assume that we encounter a function that clashes with a function of the same name in the target code. What to do? To illustrate the problem in Listing 5, I added a function called myFunction to EventHandler.cpp.
Listing 5 Our Source Code Just Before Porting the New Code
void myFunction(void) { cout << "Hello from original myFunction(void)\n"; }
So, after porting the code we now have the following illegal situation in EventHandler.cpp:
Listing 6 Duplicate Symbols in the Merged Code
void myFunction(void) // The old function { cout << "Hello from original myFunction(void)\n"; } void myFunction(void) // The newly ported function { cout << "Duplicate myFunction(void)\n"; };
So, we now have two functions in the one compilation unit with the same name. To illustrate a solution using namespaces, take a look at Listing 7, in which we add two new user-defined namespaces: one called originalCode and the other called duplicateSymbols.
Listing 7 Two New Namespaces to Solve the Symbol Clash
namespace originalCode { void myFunction(void) { cout << "Hello from original myFunction(void)\n"; } } namespace duplicateSymbols { void myFunction(void) { cout << "Duplicate myFunction(void)\n"; }; }
In Listing 7, we can see the two newly added namespaces called originalCode and duplicateSymbols, respectively. Now, I can call these functions as and when I like with the following code in Listing 8:
Listing 8 Qualified Symbol Names Using the Namespaces
originalCode::myFunction(); duplicateSymbols::myFunction();
As you can see, the calls to myFunction() are now qualified with a namespace and the scope resolution operator ::. In a way, we’ve added something to the name of each of the duplicate functions, and that something is a namespace.
Clearly, another solution is to rename the incoming (or ported) version of myFunction(), but I wanted to show how to solve the problem using namespaces. This approach has the merit that it would get the ported code compiling fairly quickly. Naturally, this solution mandates that any other calls to these functions be qualified similar to Listing 8.