简体   繁体   中英

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.

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;

Move your global declaration to a common header, like common.h :

#ifndef COMMON_H_
#define COMMON_H_

extern int g_x;   //tells the compiler that g_x exists somewhere

#endif

print.cpp :

#include <iostream>

#include "print.h"
#include "common.h"

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

source.cpp :

#include <iostream>
#include <limits>

#include "print.h"
#include "common.h"

int g_x;

int main()
{
    g_x = 5;   //initialize global var
    Print();

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

    return 0;
}

In other .cpp files, you can access g_x including the common.h header.

extern int g_x;

belongs to .h, and you need to add

int g_x =5; 

to some of .cpp.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM