Search code examples
microcontrollerpicpic18mplabmplab-c18

How to have more than one source file with C18 in MPLAB?


In many languages, such as C++, having lots of different source files is normal, but it doesn't seem like this is the case very often with PIC microcontroller programs -- at least not with any of the tutorials or books I've read.

I'm wondering how I can have a source (.c) file with a bunch of routines, global variables and defines in it that can be used by my main.c file. Is this even possible?

Thanks for your advice!


Solution

  • This is absolutely possible with PIC development. Size is certainly a concern both from a code and data perspective but it's still just C code meaning most (see compiler documentation for exceptions) of the rules of C apply including having multiple source files that get compiled and linked into a single output (usually .hex file). For example, in a separate C file from your main.c like test.c:

    int AddNumbers(int a, int b)
    {
      return a + b;
    }
    

    You could then define that in a header file test.h:

    int AddNumbers(int a, int b);
    

    Include test.h at the top of your main.c file:

    #include "test.h"
    

    You should then be able to call AddNumbers(4,5) from main.c. I have not tested this code but provide it simply as an example of the process.