Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

2.2. Ensuring You Have Only One Instance of a Variable Across Multiple Source Files

Problem

You need the same variable to be used by different modules in a program, and you can only have one copy of this variable. In other words, a global variable.

Solution

Declare and define the variable in a single implementation file in the usual manner, and use the extern keyword in other implementation files where you require access to that variable at runtime. Often, this means including the extern declarations in a header file that is used by all implementation files that need access to the global variable. Example 2-3 contains a few files that show how the extern keyword can be used to access variables defined in another implementation file.

Example 2-3. Using the extern keyword

// global.h
#ifndef GLOBAL_H_  _ // See Recipe 2.0
#define GLOBAL_H_  _

#include <string>

extern int x;
extern std::string s;

#endif

// global.cpp
#include <string>

int x = 7;
std::string s = "Kangaroo";

// main.cpp
#include <iostream>
#include "global.h"

using namespace std; 

int main() {

   cout << "x = " << x << endl;
   cout << "s = " << s << endl;
}

Discussion

The extern keyword is a way of telling the compiler that the actual storage for a variable is allocated somewhere else. extern tells the linker that the variable it qualifies is somewhere in another object file, and that the linker needs to go find it when creating the final executable or library. If the linker never finds the extern variable you have declared, or ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page