Yahoo Groups archive

Lpc2000

Index last updated: 2026-04-28 23:31 UTC

Message

RE: [lpc2000] Re: Global Variables

2005-09-26 by David Hawkins

> > 
> > The code is segmented to several C files by function, and a few 
> > variables are shared across functions. I defined those variables in
> > the first compiled C file, however the other functions in subsequent
> > files doesn't see them during the compile. I rather not lump
> > everything into one file therefore I wanted to define global variables
> > for all C files.

Hi,

It is generally good practice not to use global variables anywhere,
unless performance of the application is critical. Instead, where
multiple functions are required to access variables, put them in
a file by themselves, or in the case where another file needs
access to a variable, provide accessors; i.e., set and get functions.

Interrupt service routines are a good example of where a global
might need to be accessed.

eg.
  So you might write code separated into files like:

  /* event_flags.h */
  extern int event_flag;

  /* event_flags.c */
  int event_flag = 0;

  /* isrs.c */  
  void my_isr(void) 
  {
     event_flag = 1;
  }

however, a cleaner approach is:

  /* event_flags.h */
  void event_flag_set();
  void event_flag_clr();

  /* event_flags.c */
  static int event_flag = 0;
  void event_flag_set() {event_flag = 1;}
  void event_flag_clr() {event_flag = 0;}

  /* isrs.c */  
  void my_isr(void) 
  {
     event_flag_set();
  }

Think of this solution as writing a C++ class using C.
The static values needed between functions are like member
functions of a class, and the API presented to the user are
like C++ member functions.

Another good example is accessing peripherals, its better
to write an API for accessing the peripheral and then
use that in your code, rather than always accessing
the registers of the peripherals directly. It makes code
more easily portable. 

Dave

Attachments

Move to quarantaine

This moves the raw source file on disk only. The archive index is not changed automatically, so you still need to run a manual refresh afterward.