5.2.1.1 Compiling a Single C File

The following is a simple C program that adds two numbers. To illustrate how to compile and link a program consisting of a single C source file, copy the code into any text editor and save it as a plain text file with the name ex1.c.

#include <xc.h>

unsigned int
add(unsigned int a, unsigned int b)
{
  return a + 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 the program by typing the following command at the prompt in your favorite terminal. For the purpose of this discussion, it is assumed that in your terminal you have changed into the directory containing the source file you just created, and that the compiler is installed in the standard directory location and is in your host's search path.

xc32-gcc -mprocessor=32MZ2048ECH100  -o ex1.elf ex1.c

This command compiles the ex1.c source file for a 32MZ2048ECH100 device and has the output written to ex1.elf, which may be loaded into the MPLAB X IDE.

If a hex file is required, for example, to load into a device programmer, then use the following command:

xc32-bin2hex ex1.elf

This creates an Intel hex file named ex1.hex.

The driver will compile the source file, regardless of whether it has changed since the last build command. Development environments (such as MPLAB X IDE) and make utilities must be employed to achieve incremental builds (see 5.2.2 Multi-Step C Compilation).

Unless otherwise specified, an ELF file (this is by default called a.out) is produced as the final output.