How to "define" global variables in C-Language headers __c language

Source: Internet
Author: User

Sometimes we want to use some global variables in more than one C program, we think of declaring variables in the header file and #include in the C file. In this case, we have to put the definition of the variable in a C file, but we do not want to do so because it will make the program look bloated. Let's take a look at how Ucos II skillfully solves this problem.

Ucos II has such a piece of code in its header file ucos_ii.h:

#ifdef   os_globals
#define  os_ext
#else
#define  os_ext  extern
#endif

Then use OS_EXT macros to declare variables, such as: Os_ext int16u osrdygrp;

Then in one of the C files containing ucos_ii.h #define OS_GLOBALS (see ucos II os_core.c). Note that this sentence must be placed before #include "ucos_ii.h", for reasons you understand (if you do not understand, and see below).


The principle of this technique is understood as long as you understand the nature of the #include "xxx.h" statement. The compiler's handling of the #include "xxx.h" statement in the compilation process is to replace the statement with the entire contents of the xxx.h. In the above example, only the #define OS_GLOBALS is defined in os_core.c, so the Os_ext macros are processed only when the file is compiled, and are treated as extern keywords in other c files.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.