4.2.2.2 Compiling Multiple C Files

This section demonstrates how to compile and link a project, in a single step, that consists of multiple C source files.

Copy the example code shown into a text file called add.c.

/* add.c */
#include <xc.h>

unsigned int add(unsigned int a, unsigned int b) {
  return a + b;
}

And place the following code in another file, ext.c.

/* ex1.c */
#include <xc.h>

unsigned int add(unsigned int a, unsigned int b);

int main(void) {
  unsigned int x, y, z;
  x = 2;
  y = 5;
  z = add(x, y);

  return 0;
}

In the interests of clarity, this code does not specify device configuration bits, nor has any useful purpose.

Compile both files by typing the following at the prompt:

xc8-cc -mcpu=16F1946
                                        -mdfp="Microchip/PIC12-16F1xxx_DFP/1.7.242/xc8" ex1.c add.c

This command compiles the modules ex1.c and add.c in the one step. The compiled modules are linked with the relevant compiler libraries and the executable file ex1.elf is created.