making sense of directives in headers

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

making sense of directives in headers

356 Views
irob
Contributor V

Hey all.  I've got some Freescale sample code and I'm trying to decode their use of compiler directives.  Here's a sampling from the project's main.h file:

 

#undef EXTERN#ifdef MAIN#define EXTERN#else#define EXTERN extern#endif#ifndef _MAIN_H#define _MAIN_H

 What's going on here?  I see they are looking for the definition of the macro "MAIN", then defining EXTERN.  But what's the point?  the reserved type "extern" is part of the language, why would it need to be defined?

 

Same goes for the macro "_MAIN_H".  Are those even necessary if the linker does the work of referring to all prototypes and macro names from this header file and associating to the main.c file?

 

I feel like my foundational questions are tipping into computer programming theory.  Perhaps I'm wrong.

Labels (1)
0 Kudos
1 Reply

239 Views
kef
Specialist I

_MAIN_H should be simple. It is often used to prevent double inclusion of H file, like

 

//start of H-file

#ifndef __MAIN_H

#define __MAIN_H

 

// H-file body

 

#endif

// end of H-file

 

Regarding EXTERN. Having lots of exported variables, it makes sense to define them in one place to avoid typing or copying errors. But while declaring variables, you need to use extern keyword, while defining the same variables you need to have no extern. And that is purpose of EXTERN. In main.c you define MAIN (or maybe better MAIN_C,) before #include "main.h". In all other files MAIN is not defined. All variables are then are defined and declared in one place, only in main.h like this:

 

EXTERN int intvar;

EXTERN char cvar;

 

  

The problem here is what to do with variable initializers like int a=10;? Initializer abandons extern keyword. So to continue using EXTERN-like stuff with initializers you probably need to use additional macros like

 

makevariable(type varname, initializer)

 

, which would expand like

.

extern type varname; //when MAIN is not defined

 

and

 

type varname=initializer; // when MAIN is defined

0 Kudos