The Open Source Swiss Army Knife

/code/cPP/
/code/cPP/ + sub-categories
http://www.sirfsup.com/
web directory content
    
      

Not logged in
Chat Register Login
return to:  http:/www.sirfsup.com      /code   /cPP 
Permalink: var_scope.htm
Title: C++ internal and external linkage
article options : please login   |  print view

source = c++ primer Sam's publishing
  1. file-scope variables with external (1 - 3) and internal (4) linkage
    1. file 1
      int errors = 20;
      file 2
      void foo() {
           cout << errors; // error
    2. file 1
      int errors = 20;       external declaration
      file 2
      int errors;       //invalid declaration
      void foo() {
           cout << errors; // error
    3. file 1
      int errors = 20;       external declaration
      file 2
      extern int errors;       //refers to errors from file1
      void foo() {
           cout << errors;
      "the keyword extern indicates a reference declaration, i.e. a declaration elsewhere.
    4. file 1
      int errors = 20;       external declaration
      file 2
      static int errors = 5;       //known to file2 only; applying the static keyword gives it static linkage
      void foo() {
           cout << errors;
      }
  2. static keyword inside a block gives a local variable with no linkage works for functions and variables alike
  3. const
    "whereas a global variable has external linkage by default, a const global variable has internal linkage by default."
    i.e. const = static
    internal linkage means that const declarations in the header can be made in each file. The extern keyword not required. Therefore each file which includes the header has its own set of constants and doesn't share them.
    so declare the header constants as constants. e.g. extern const int states = 50;. Of course, declare merely s const int states = 50; in each additional source file.

    Leave a Reply
    Your Name:     anonymous
    Your Email:
    Website:  
    Comments:

    The author will be notified of your reply.
    return to top