1

I have a problem with a shared variable. I compile all the files and first run server.c and second run client.c. This is my file server.c:

#include "server.h"
int port;
int main()
{
    port = 4;
}

This is my file server.h:

int port;

This is my file client.c:

#include <stdio.h>
#include "server.h"
extern int port;
int main()
{
    printf("PORT is %d\n", port);
}

The output is

PORT is 0

Why is the number not 4?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Adam Barča
  • 51
  • 1
  • 10
  • 2
    Because you have two different programs here which do not share anything in the runtime. – Eugene Sh. Mar 05 '20 at 18:48
  • The client and the server are different programs. The declaration in `server.h` is inappropriate — [it should be `extern int port;`](https://stackoverflow.com/q/1433204/15168). If you include `server.h`, you don't need the `extern int port;` in `client.c` — but you do need to ensure that the client program defines the `port` variable. Your header should probably include `enum { DEFAULT_PORT_NUMBER = 1234 };` or something similar (`#define DEFAULT_PORT_NUMBER 1234` — see [`static const` vs `#define` vs `enum`](https://stackoverflow.com/q/1674032/15168)). – Jonathan Leffler Mar 05 '20 at 18:49
  • Your two files containing `main()` would then each define `int port = DEFAULT_PORT_NUMBER;`. The variables in different programs are completely separate. If you had library code (code shared between the client and server programs), then it could be the correct place to define `int port = DEFAULT_PORT_NUMBER;`. Note that port numbers less than 1024 are reserved for privileged processes (root privileges on Unix systems). Hence my choice of `1234` rather than `4` for the port number. – Jonathan Leffler Mar 05 '20 at 18:51
  • "share variable" Do you mean share a default value (e.g., defined in a common header file) or do you mean share the same address space for a given variable? When I think of the names of your C files, I think of the latter. – Jeff Holt Mar 05 '20 at 19:03
  • 2
    `server.h` should be `extern int port;` Otherwise, without `extern` you declare storage in every compilation unit including server.h and potentially create a linker issue. But that's not the root of your issue - it's having two mains. – selbie Mar 05 '20 at 19:23
  • When you write #include "server.h" it just means: copy everything from the file called "server.h" and paste it here. So, the port variable is by no means shared between your programs, and each one has its own "port" variable, that is why interacting with it in one program has no effect in the other. If you were to use both of these c files in a single application by compiling and then linking them together, that would be a different story (you would also need to delete one of the main functions, since there cannot be more than one in a single application). – Meliodas Mar 05 '20 at 19:47

0 Answers0