Cpp - class extern

Introduction

We can use extern to reference global variables. In this way we tell the compiler that we are using the global variable not a new one.

Source file 1

#include <iostream> 
#include <string> 
using namespace std; 

void cutline( void );         // Prototype 
string line;                  // Global string 

int main() 
{ 
    while( getline(cin, line)) // As long as a line 
    {                          // can be read. 
       cutline();               // Shorten the line. 
       cout << line << endl;    // Output the line. 
    } 
    return 0; 
} 

Source file 2

In the following code we are using the extern keyword to mark line variable.

#include <string> 
using namespace std; 

extern string line;             // extern declaration 

void cutline() 
{ 
    int i = line.size()-1; // Position after the 

    line.resize(i--);    // Fix new length. 
} 

Related Topic