Approach for Removing Globals

I have a basic approach for identifying and removing global variables from source code. It is an iterative approach that converges slowly and that should be automated if it were to be repeated often. Basically, I work file at a time, starting with headers and then into file-specific code and then actual bodies of the routines. The goal is to remove global variables and statics to make the code reentrant and thread-safe.

The steps are simple, if tedious.

Identify global variables
Use nm to do this.
         nm gram.o | grep ' [CcDdBbRr] '
      
See the output from gram.o for an example.
This identifies the non-local variables. Lower case letters indicate statics.
Remove these variables.
This can be done by grouping them and collecting them in structs and creating a global instance of the struct For example, in gram.c again we group the the variables into a structure and name it R_ParserState. Note that we use the same names as the original variables but prefixed by `_'
/* Internal lexer / parser state variables */
/* 
  Make the static variables local to an instance of the parser.
  We put them into a struct to collect them and then 
  refer to them using the local variable referring to this
  parser instance.
*/
typedef struct {
 int	_EatLines;
 int	_GenerateCode;
 int	_EndOfFile;
  int	(*_xxgetc)(R_Evaluator *);  /* Added arguments to typedef. */
 int	(*_xxungetc)(int, R_Evaluator *);

  /* Moved from just above ParseInit. */
 int	_SavedToken;
 SEXP	_SavedLval;
 char	_contextstack[50];
 char  *_contextp;
 } R_ParserState;

At this point, we would have to change the code to refer to these variables as elements in a global variable such as ParserState->_EatLines. Rather than changing the myriad of references to these, we create macros such as

        #define EatLines ParserState->_EatLines
      
and this basically preserves the original semantics.
  • As Rob says, "some globals are needed"
    create macros to refer to elements of the struct under the original variable names (i.e put foo in a field

  • Duncan Temple Lang <duncan@research.bell-labs.com>
    Last modified: Thu May 27 19:02:29 EDT 1999