A reader just wrote in today asking for an extension to the example that begins in the Sharing Variables Among Source Files section of C++ All-In-One Desk Reference For Dummies. The example shown in Listings 5-6, 5-7, and 5-8 describes how to declare a global int variable using extern and the reader wanted to extend this example to the string type. The reader had tried several times, but kept getting the following error message (the same message appears in CodeBlocks 8.02 and 10.05 and the update in this post works with both versions):
error: ‘string’ does not name a type
I’m assuming that you’ve already read the discussion about this example (be sure you read the entire section from pages 119 to 121). Creating a fix for this problem isn’t hard, but providing some example code will make things easier to understand. The first issue is to include the required support in main.cpp (shown in Listing 5-6). Here’s an updated version that includes an entry for a string variable named CheeseburgerType.
As you can see, you must provide #include <string> and then set CheeseburgerType to a value, which is “Deluxe” in this case. Otherwise, the example works precisely the same as before.
Let’s look at sharealike.h next (Listing 5-7). The following code changes are essential or the example will never work.
Notice the inclusion of using namespace std;. The example will fail to compile without this statement added unless you specify the namespace as part of the type declaration. Once you define this addition, you can create the extern string CheeseburgerType; declaration. Of course, if string were part of another namespace, you’d use that namespace instead.
The final part of the puzzle is to create the required implementation. This part appears in sharealike.cpp (Listing 5-8). Here’s the final piece of the example:
As with main.cpp, you must add the appropriate #include. In addition, this part of the example updates EatAtJoes() to include CheeseburgerType in the output. When you run this example, you’ll now see a cheeseburger type in the output as shown here:
Are there any questions on this extension? Please let me know at John@JohnMuellerBooks.com.