How not to use global variables in c
I have read the writing on the wall, Avoid Globals. Which leads to the obvious question, how best to do it?
I obviously want to do it with a current project. The goal is to let a distant PC send "keystrokes" to applications that already have an stdin reader. The idea is to let the existing code detect there is no pending keystroke, then check if there is a "udp keystroke" and, if so, stuff it in so it appears to be keyboard input. Minimally invasive and won't require gobs of retro-fitting in other people's code.
So I cobbled up a small UDP socket reader that uses a setup()
function to open and bind the port, then a service()
function in a loop that uses a nonblocking select()
once, no loop, just check if there is anything to read right now. If so, read the data from the socket and do something with it, else return a 0.
// pseudo c
char c;
setup();
while (1)
{
c = check_for_keyboard_entry();
if ( c == 0 )
c = service();
handle_keypress( c );
do_a_bunch_of_other_stuff();
}
The obvious way to do this is with a few globals to transfer the port, timeout, sockaddr's etc. between the two functions. But, thou shalt avid globals, right?
So what is a preferred way to transfer the six or eight vars between the functions?
If I were to use static vars in the setup()
, would they be accessible by the service()
routine?
I suppose a struct that gets malloc-ed and passed around would work. I'd ought to have a cleanup()
to close the socket and free the memory.
REMEMBER, THIS IS AC QUESTION. NO C++!
You can just pack all that information into a struct
. The struct can be visible to the client or an opaque type. An opaque type may be a better choice so you can hide the data (encapsulation) for complex types.
typedef struct {
port_t port;
timeout_t timeout;
sockaddr_t sockaddr;
etc_t etc;
} my_stuff;
then pass it around by reference:
void Foo(my_stuff*);
I suppose a struct that gets malloc-ed and passed around would work. I'd ought to have a cleanup() to close the socket and free the memory.
Generally, a struct would not always need to be malloc
'ed. But yes, this may be a case where it is required.
上一篇: 你如何检查选择器是否匹配jQuery中的某些东西?
下一篇: 如何在c中使用全局变量?