Search code examples
c++global-variablesextern

How to use global variables in multiple .cpp files?


I have this simple program which tries to print my global variable in a separate file. I'm using the Visual Studio 2013 professional IDE.

print.h

#ifndef PRINT_H_
#define PRINT_H_

void Print();

#endif

print.cpp

#include "print.h"

#include <iostream>

void Print()
{
    std::cout << g_x << '\n';
}

source.cpp

#include <iostream>
#include <limits>

#include "print.h"

extern int g_x = 5;

int main()
{
    Print();

    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cin.get();

    return 0;
}

I get a compiler error error C2065: 'g_x' : undeclared identifier.

I've searched through this forum and was unable to find anyone else having my problem. I've tried re-declaring my global variable in the separate .cpp file with no success. As you can see, I've included the necessary header guards and assigned my global variable the extern keyword. This is my first time testing global variables in multiple files. Obviously I'm missing something simple. What do I need to change or add to make my program work?

EDIT: I found this topic useful in understanding the difference between extern and the definition of a global variable.


Solution

  • The compiler is compiling print.cpp. It knows nothing about source.cpp while it is compiling print.cpp. Therefore that g_x that you placed in source.cpp does you absolutely no good when print.cpp is being compiled, that's why you get the error.

    What you probably want to do is

    1) place extern int g_x; inside of print.h. Then the compiler will see g_x when compiling print.cpp.

    2) in source.cpp, remove the extern from the declaration of g_x:

    int g_x = 5;