ARM Technical Support Knowledge Articles

DECLARING VARIABLES IN HEADER FILES

Applies to: General Topics

Answer


Information in this article applies to:


QUESTION

Is there an easy way to declare my variables in a header file and create extern definitions for them as well?

ANSWER

Yes. 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.

Article last edited on: 2005-02-05 14:45:50

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential