How to share variable in two C++ files

后端 未结 3 1402
温柔的废话
温柔的废话 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.

提交回复
热议问题