|
|||||||||||
Technical Support Support Resources
Product Information |
GENERAL: DECLARING VARIABLES IN HEADER FILESInformation in this article applies to:
QUESTIONIs there an easy way to declare my variables in a header file and create extern definitions for them as well? ANSWERYes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files. However, if you must, the following technique may be used to declare variables and define them using the same header file. First, create a header (called VARS.H) as follows: /*---------------------------------------------------------------------------- VARS.H Note: #define VAR_DECLS 1 before including this file to DECLARE and INITIALIZE global variables. Include this file without defining VAR_DECLS to extern these variables. ----------------------------------------------------------------------------*/ #ifndef VAR_DEFS // Make sure this file is included only once #define VAR_DEFS 1 /*---------------------------------------------- Setup variable declaration macros. ----------------------------------------------*/ #ifndef VAR_DECLS # define _DECL extern # define _INIT(x) #else # define _DECL # define _INIT(x) = x #endif /*---------------------------------------------- Declare variables as follows: _DECL [standard variable declaration] _INIT(x); where x is the value with which to initialize the variable. If there is no initial value for the varialbe, it may be declared as follows: _DECL [standard variable declaration]; ----------------------------------------------*/ _DECL int var_a _INIT(100); _DECL int var_b; _DECL int var_c _INIT(27); #endif /*---------------------------------------------------------------------------- ----------------------------------------------------------------------------*/ VARS.H declares 3 global variables as follows: int var_a = 100; int var_b; int var_c = 27; Second, in exactly one source file, include the following #define prior to including the VARS.H file: #define VAR_DECLS #include "vars.h" #define VAR_DECLS causes the VARS.H include file to actually declare and initialize the global variables. Finally, in all other source files (which use these variables) simply include the VARS.H header file: #include "vars.h" Be sure that VAR_DECLS is not defined in these other files or else your variables will be declared twice. FORUM THREADSThe following Discussion Forum threads may provide information related to this topic.
Last Reviewed: Saturday, February 5, 2005 | ||||||||||
|
Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.