Dig into the use of global variables in uCOS

  • 2020-04-01 23:32:27
  • OfStack

Global variables are often encountered in C programming. Global variables are generally defined in the following way

Defined in the.c file

Unsigned int gVariable;

Declaration in the.h file

Extern unsigned int gVariable;

The purpose of this is to prevent variable duplication and improve compilation efficiency. But there are all kinds of problems that can arise if the schedule is not right. Repeated declarations at compile time and even errors.

Reading the book uC/os-ii translated by shao beibei, I found that it used a very clever method of global variable definition. Now I will make a record of my understanding, which is my own notes. Also write out and learn together.

A global header file includes. H is defined in uC/ os-ii. This file is referenced in any.c file.

Each of these.h files defines such a macro. \


#ifdef XXX_GLOBALS
#define XXX_EXT
#else
#define XXX_EXT extern
#endif

Each global variable in the.h file is prefixed with xxx_EXT. XXX stands for the name of the module. The.c file of the module has the following definition:

# define XXX_GLOBALS

# include "includes. H"

When the compiler processes the.c file, it forces xxx_EXT (found in the corresponding.h file) to be null (because xxx_GLOBALS is already defined). So the compiler allocates memory space for each global variable, and while the compiler works with other.c files, xxx_GLOBAL is not defined and xxx_EXT is defined as extern so that the user can call external global variables. To illustrate this concept, see uC/ os_ii.h, which includes the following definition:


#ifdef OS_GLOBALS
#define OS_EXT
#else
#define OS_EXT extern
#endif

OS_EXT INT32U OSIdleCtr;
OS_EXT INT32U OSIdleRun;
OS_EXT INT32U OSIdleMax;

Meanwhile, ucos_ii.h has the following definition:

# define OS_GLOBALS

# include "includes. H"

When the compiler processes ucos_ii.c, it makes the header file look like this because OS_EXT is set to empty.

INT32U OSIdleCtr;

INT32U OSIdleRun;

INT32U OSIdleMax;

The compiler then allocates these global variables in memory. When the compiler processes other.c files, the header file looks like this, because OS_GLOBAL is not defined, so OS_EXT is defined as extern.

Extern INT32U OSIdleCtr;

Extern INT32U OSIdleRun;

Extern INT32U OSIdleMax;

In this case, no memory allocation is generated, and any.c file can use these variables. This is defined only once in the.h file.


Related articles: