This is a simple example on how to use the same variable across multiple files using Microchip C32 compliler. The main file (with void main(void) in it) is source-file-one.c. It has the include statement for source-file-two.h.
The variable globalvariable is defined in the main source file, and then refered to in source-file-two.c using the extern command.
The #warning statements are there only to see how the compiler compiles each part. They can be left out without any impact.
********************* source-file-one.c *************************
#warning begin source-file-one.c
#include <plib.h> // so Nop() is recognised
#include "source-file-two.h"
int globalvariable; // this is where you declare the variable
int main(void)
{
initGlobalVariable();
while(1)
{
if (globalvariable > _MAX_GLOBAL_VARIABLE_VALUE)
{
globalvariable = 0;
}
else
{
incrementValue();
}
Nop(); // something to put a break point on
}
}
#warning end source-file-one.c
******************** source-file-two.h **********************
#warning begin source-file-two.h #ifndef _SOURCEFILETWO_H #define _SOURCEFILETWO_H #warning including source-file-two.h main content #define _INCREMENT_VARIABLE_BY 2 #define _MAX_GLOBAL_VARIABLE_VALUE 500 void incrementValue(void); void initGlobalVariable(void); #endif #warning end source-file-two.h
**************** source-file-two.c ******************
#warning begin source-file-two.c
#include "source-file-two.h"
extern int globalvariable; // declare variable as a variable in another file
void incrementValue(void)
{
globalvariable = globalvariable + _INCREMENT_VARIABLE_BY;
}
void initGlobalVariable(void)
{
globalvariable = 0;
}
#warning end source-file-two.c