How does C ++ distinguish between calling a global variable and declaring a global variable?

This is the most confusing part for me from the section on Global Variables and Binding Properties.

  extern int g_var1;

      

The statement can be something like this when defining an external non-console global variable. I think I will be writing exactly the same way as using this variable (via a forward declaration) in another file. If both statements are the same, then how does C ++ know if a variable has been specified or defined in a file?

+3


source to share


3 answers


When you say extern int g_var1;

this variable is just declared and later when you use it you can use it directly.

file1.cpp:

int g_var1;

      



File2.cpp:

extern int g_var1;

      

You don't have to write extern

every time. Although I would suggest, if you need to use global variables, put them in a separate header file.

+1


source


If I understand your question correctly, you shouldn't write exactly the same in another file (namely, you shouldn't write "extern int g_var1" in two files). It is good practice to declare some variable global in the header file; make a definition in the cpp file that includes this header file. After that, you can use this variable in all files that will include the header file.

To illustrate, an example would be something like this:

variables.hpp

#pragma once
extern int g_var1;

      



variables.cpp

#include "variables.h"

int g_var1 = 1;

      

main.cpp

#include "variables.h"
#include <iostream>

using namespace std;

int main(){
    cout << g_var1 << endl;
}

      

+3


source


Form approval

extern int g_var1; // this is a declaration

      

- variable declaration. The extern keyword guarantees this. If you write

int g_var1; // declare and define variable

      

you define it as well. You can declare a variable as many times as you like, but only define it once. Therefore you can write

extern int g_var1;

      

in those files where you need to use the variable. Then, when linking, the compiler will resolve the definition of the variable (assuming you give the definition in some file, of course).

+2


source







All Articles