Source of storage_linkage_main4.cpp


  1: //storage_linkage_main4.cpp
  2: //Goes with storage_linkage_aux4.cpp. Compile the two files
  3: //separately and link the object files to produce an executable,
  4: //but first activate the same numbered comment in each file.
  5: //There are three such pairs of numbered comments.
  6: //Illustrates the difference in the "default linkage" of global
  7: //variables as compared to global constants.

  9: #include <iostream>
 10: #include <string>
 11: using namespace std;

 13: int main()
 14: {
 15:     //extern string myName;       //1
 16:     //extern const string myName; //2
 17:     //extern const string myName; //3
 18:     cout << endl << myName;
 19:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 20: }

 22: /*
 23: Questions:
 24: 1. What happens when comment //1 is activated in both this file and
 25:    the companion file?
 26: 2. What happens when comment //2 is activated in both this file and
 27:    the companion file?
 28: 3. What happens when comment //3 is activated in both this file and
 29:    the companion file?


 32: Answers:
 33: 1. The name "Porter Scobey" is output. This is just the "usual"
 34:    case of a global (and, by default, extern) variable in one
 35:    file being accessed from another file in the same compilation
 36:    unit.
 37: 2. This time there is a link error because, unlike global variables,
 38:    global constants are *not* extern by default and thus have internal
 39:    linkage. This means they are not visible (by default) in any other
 40:    file.
 41: 3. The name "Porter Scobey" is output. This is because we have added
 42:    the keyword "extern" to the constant definition in the companion
 43:    file, thus giving it external linkage and making it visible in
 44:    this file.
 45: */