user5117637
user5117637

Reputation:

How C++ differentiates between a call to global variable and declaration of a global variable?

This is the most confusing part for me from section Global Variables and linkage properties.

  extern int g_var1;

Statement could be something like this when defining an external non-const global variable. I think I will write exactly the same for using that variable (through forward-declaration) in some other file. If both the statements are same, how C++ knows whether the variable was declared or was defined in a file?

Upvotes: 3

Views: 579

Answers (3)

Nishant
Nishant

Reputation: 1665

When you say extern int g_var1; the variable is just declared, and later when you have to use it you can use it directly.

file1.cpp:

int g_var1;

File2.cpp:

extern int g_var1;

You need not to write extern everytime. Though i would suggest if you have to use global variables place them in a separate header file.

Upvotes: 0

jensa
jensa

Reputation: 2890

A statement of the form

extern int g_var1; // this is a declaration

is a declaration of a variable. The keyword extern makes sure of 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 define it only once. You could therefore write

extern int g_var1;

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

Upvotes: 1

ozdm
ozdm

Reputation: 153

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). A good practice is to declare some variable global in a header file; make the definition in a cpp file that includes this header file. After doing this, you can use this variable in all of the 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;
}

Upvotes: 2

Related Questions