As you can see in the Title box, I´d like to find a way how to use my sockets in multiple cpp files.
slisten = socket(AF_INET,SOCK_STREAM, 0);
//and so on...
This is the way I use the
ws2_32.lib but just in main. I´d like to use the socket
clientin other files, so I`m able to send data wherever I want. The socket is declared as a global variable. I´d be nice if someone can give me an advice.
Thanks in advance.
Best How To :
This question seems not specific to sockets, but to global variables in general. If you need to create a global variable (a socket, in this case) which must be accessible by multiple compilation units:
- You define the global variable in one single compilation unit (i.e. one cpp file)
- You declare the variable with the
extern statement in all the other compilation units that need to use it.
Some further information:
- If your program is multithreaded, you will need to protect the global variable from concurrent usage through a
- The order of inizialization of global variables across different compilation units has undefined behavior. This is known as static initialization order fiasco. You can impose a specific order by using, e.g. the SIngleton or a some kind of Factory design patterns.