Linking Files with Hi-Tech C
When writing programs for the PIC, there are certain things that you will want to do that aren’t specific to one particular project. Â The functions written to perform these tasks might also be rather large and make the main function longer than desired. Â Or perhaps the function is specific to this project but makes the main function too cluttered. Â Or perhaps there are a collection of related functions that would best be grouped together. Â Whatever reason you may have for storing a function outside of main.c you can do it by linking the files.
You will need to create a c file in which to place the function, named in a way that works best for your situation. Â Something descriptive of what the function does would be best. Â This file will need all the normal appropriate headers, such as htc.c and/or stdio.c. Â Besides these files, you will need to link to another header file that you will make. Â The creation of the header file will be covered later, but the formatting for the header is
#include
#include "wait.h"
Note the use of quotations instead of brackets.
Now, in the file itself the code will be placed just like any normal function. Below is a sample of a dummy wait function as it were to appear in it’s own file.
#include
#include "wait.h"
void wait(unsigned int time) {
int count;
for (count = 0; count < time; count++;> continue;
}
If this is saved without first creating the header file, it will create an error. Do not worry about this until you’re finished with everything.
The header file is quite simple. For the example above, the header file in its entirety would be as follows:
#ifndef WAIT_H_
#define WAIT_H_
#endif /*WAIT_H_*/
void wait(unsigned int time);
The first three lines are inserted by Hi-Tide upon creation of the h file. If more than one function is defined in the c file, each function needs its own lines with the correct parameters.
In order to use the functions in the main c file, simply include the link to the header file at the top of your program. They can then be used as if they were attached at the bottom or top of the file.
Most of the errors I encounter involve forgetting to put the proper headers on the files or not changing the h file after changing the function or adding a function to the c file. If you run into an error involved with the functions in these separate files, check those two points first.