Search code examples
c++global-variablesextern

can global variables be accessed and modified in various classes in C++


I have run into code spaghetti where i need to instrument flow control i.e., send data one at a time. How can i use global variable to solve this? If global variables don't work, what is the way to access and modify variables in multiples functions which could be in different classes

I tried the following (I am pasting partial code) but it gave me ld error that I could not resolve. I want to ask what might be the best and clean approach to solve this.

file1.h

int data_received; //global variable
class abc
{
.
.
.
public:
  void send_data(..)
.
.
.
};

file1.c

void send_data()
{
  while(!end_of_file)
  {
    read_line;
    data_received = 0;
    transmit_data(line);
    while(data_received == 0)
      cout<<"waiting for response before proceeding\n";

  }

}

file2.c

//data receive class

void transmit_data()
{
 ....
 ....
 ....
//data sent upstream
 data_received = 1;
}

I have searched many posts on stackoverflow but there is no clear answer. Some suggest to use extern variable but no clear example of external variable being modified in more than one class functions.


Solution

  • Please learn more about

    • Declare vs Define in C and C++.
    • compile vs link

    define global variable

    // file1.cpp
    int data_received; 
    

    extern tell complier that data_received can be found when linker.

    // file2.cpp
    extern int data_received;
    

    in addition, static can limit my_global_var only to be used in file defining it. example

    // file3.cpp
    static int my_global_var = 1;
    

    Error will be occured in linker

    // file4.cpp
    extern int my_global_var;