How to share variable in two C++ files

后端 未结 3 1403
温柔的废话
温柔的废话 2021-01-17 06:22

I am trying a code which has two C++ files(client.cpp and server.cpp) and one common.h header file which contais a class and functions

相关标签:
3条回答
  • 2021-01-17 06:45

    This isn't going to work the way you think. You are compiling like this: "g++ server.cpp common.h -o server". That tells me that you are probably also compiling the client like this (or something similar): "g++ client.cpp common.h -o client".

    This is going to create two separate executables. If you were compiling them into one program, you could do as the other answers suggest here: move int ch; into the global scope (outside of any functions, including main) of exactly one of the files, and ch would be shared between both files.

    But you're not doing that - you're creating two entirely separate programs. You can't have a shared global variable between two programs. You need to use some other method of communicating such as a sockets or TCP. If they're running on the same system, you could also use a simple hack like having one process write to a text file that the other reads.

    0 讨论(0)
  • 2021-01-17 07:00

    What you want will only work only in single compilation. To share variable between translation units you must move int ch=1; to global scope, outside any function. Then you can reference it from other translation unit if you declare it extern int ch;

    To share some data between two different applications you must use some Inter Process Communication mechanism. The simplest one is some external file. This is a broad topic, you can find many answers on SO: Sharing same variable between more than one independent programs in Linux

    For platform independent solution I suggest using boost::interprocess library: http://www.boost.org/doc/libs/1_60_0/doc/html/interprocess/sharedmemorybetweenprocesses.html

    0 讨论(0)
  • 2021-01-17 07:02

    in one and only one C file write (without extern) at main level (not in function)

    int ch;

    BUT not declare in main, beause the first will be hidden, You can set value

    ch = 1;

    but not declare;

    0 讨论(0)
提交回复
热议问题