Ensuring You Have Only One Instance of a Variable Across Multiple Source Files - C++ Preprocessor

C++ examples for Preprocessor:Directive

Introduction

Declare and define the variable in the usual manner, and use the extern keyword in other implementation files.

// global.h
#ifndef GLOBAL_H__
#define GLOBAL_H__

#include <string>

extern int x;
extern std::string s;

#endif

// global.cpp
#include <string>

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

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

using namespace std;

int main() {

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

Related Tutorials