How to not use global variables in c

I read the letter on the wall, Avoid the Globals. Which leads to an obvious question, what is the best way to do this?

I obviously want to do this with the current project. The goal is to allow the remote computer to send "keystrokes" to applications that already have a stdin reader. The idea is to allow existing code to detect the absence of a pending key press and then check if there is an udp keystroke, and if so, enter it so that it looks like a keyboard. Minimally invasive and will not require clogging the retro fitting in other people's code.

So, I exhausted a small UDP socket reader, which uses the setup() function to open and bind a port, and then a service() function in a loop that uses non-blocking select() once rather than a loop, just check there is something to read. If so, read the data from the socket and do something with it, otherwise return 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 global variables for port transfer, timeout, sockaddr, etc. between two functions. But, you will be a greedy global, right?

So what is the preferred way to transfer six or eight vars between functions?

If I used static vars in setup() , would they be accessible using the service() procedure?

I believe that a structure that receives malloc-ed and is passed will work. I would have to cleanup() close the socket and free up memory.

REMEMBER THIS IS A QUESTION C. NO C ++!

+7
c struct global-variables
source share
1 answer

You can simply pack all this information in a struct . The structure may be visible to the client or an opaque type. An opaque type may be the best choice, so you can hide data (encapsulation) for complex types.

 typedef struct { port_t port; timeout_t timeout; sockaddr_t sockaddr; etc_t etc; } my_stuff; 

then pass it by reference:

 void Foo(my_stuff*); 

I believe that a structure that receives malloc-ed and is passed will work. I would have to clear () to close the socket and free up memory.

Typically, the structure does not always have to be malloc 'ed. But yes, this may be the case when it is necessary.

+3
source share

All Articles