-2

I want to Use one globe variable in all cpp files.If one class of the cpp file changed the value,I want to access it from another class cpp file,which is the value that least modified by any other cpp class file.

str.h - global variable file

#ifndef MY_PROG
#define MY_PROG
extern char * myname;
#endif

class1.cpp

#include "str.h"
char * myname; 
class class1
{
   class1(){}
   ~class1(){}
   void Setname1(char *name) { myname = name }
};

class2.cpp

#include "str.h"
char * myname; 
class class2
{
   class2(){}
   ~class2(){}
   void setName(char *name) { myname = name } 
};

class3.cpp

#include "str.h"
class class3
{
    class3(){}
    ~class3(){}
    char *GetData()
    {
           return myname;
    }
};

main.cpp

#include "str.h"
int main()
{
  class1 c1;
  class2 c2;
  c1.Setname1("XXXX");
  c2.setname("YYYY");
  class3 c3;
  cout << c3.GetData;
}

when I execute the program, I need to get Last modified value that is "YYYY" .I am new to cpp, And also please tell me whether I used the extern keyword correctly.If not , please provide me the right procedure.

AADHI A.R
  • 35
  • 6

1 Answers1

0

The essential in your problem is understanding the difference between declarations and definitions of variables (and types, functions etc. objects in C/C++)

extern char * myname; is a declaration. It makes myname visible to other pieces of code in the same file so that they can reference it.

char * myname; is a definition. Not only it makes myname visible, it also instructs the compiler to allocate space for it and to make its address known.

You can have as many declarations of the same variable in your code as you want, as long as they do not contradict each other. No so with definitions. If you define a thing two times, it would need to be assigned two addresses, and then how can other object files "understand" which address to use when referencing it? The same goes with the space allocated — what to do with the extra piece of it allocated? This is the error that you see.

To make the code work, have only one and exactly one definition of myname in exactly one file. It must not be a header file because it gets copied into multiple source files thus creating multiple definitions. It can be any other C++ file though.

In the rest of the files (or in a single header included in all of them) have multiple declarations of myname if it is referenced in a particular file. If not, you can omit it for a particular unit.


All this being said, it is considered to be a VERY BAD PRACTICE to communicate data between compilation units through global mutable shared variables. They make code a nightmare to debug and understand and impossible to parallelize. Nobody ever thinking getting money for the code they write should use them. Instead, the best approach would be to pass a mutable object as one of methods/functions argument. Details actually depend on the rest of your application.

Grigory Rechistov
  • 2,104
  • 16
  • 25