0

Is there any way to use from two diffrent source files the same instance of variable in C++ ?

for example,if I have

source1.cpp

x = true;
while (x) 
{

}

source2.cpp

x = false;

then if I run first source1.cpp,there is infinite loop,and after runing source2.cpp from diffrent terminal,the loops end,due to x changes.

thanks.

just to make it clear : those are two main files compiled separate from each other and run at the same time from two diffrent terminals

Matan
  • 109
  • 2
  • 13
  • That is called an "extern variable" – Jonas Jan 07 '17 at 06:38
  • Can you extend how to do it? I try a lot with extern or static and nothing really worked – Matan Jan 07 '17 at 06:48
  • Re ["should be run from two diffrent terminals at the same time"](http://stackoverflow.com/questions/41518583/using-same-variable-in-diffrent-source-files-c#comment70243893_41518930), are you talking about two different programs, or two different processes of the same program, or two different translation units in the same program? – Cheers and hth. - Alf Jan 07 '17 at 07:50
  • two diffrent programs(server program and client program) – Matan Jan 07 '17 at 08:25
  • @Matan: then, you are asking about a total different problem, which is how to share a variable between separate processes. I suggest you rewrite your question in that sense. – Michaël Roy Jun 13 '17 at 16:58
  • @Matan: If the main idea of having both a client and a server app is sharing _x_, then your apps are missing the entire client and server implementations. There are many examples of such applications around on the internet. You should visit this page http://www.thegeekstuff.com/2011/12/c-socket-programming/?utm_source=feedburner to get an idea on how it's done. – Michaël Roy Jun 13 '17 at 17:11

1 Answers1

0

"The global variable should be declared extern in a header file included by both source files, and then defined in only one of those source files" Check out this post

MistaGoustan
  • 346
  • 6
  • 21
  • I've tried this already, my problem is that source1.cpp and source2.cpp are two diffrent main files compiled seperate from each other.and then it should be run from two diffrent terminals at the same time,as I wrote in the first msg – Matan Jan 07 '17 at 07:27
  • ahh my apologies. how about you write and read to a static file? or is that to insecure for what you are dealing with? – MistaGoustan Jan 07 '17 at 07:37
  • well I thought about doing this,but I will use it only in case no other solution in C++ exist – Matan Jan 07 '17 at 07:46
  • Yeah I agree it's a last resort. Wish i was more help. Good luck. – MistaGoustan Jan 07 '17 at 07:47