3.2.2.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.
xc8-cc
-mcpu=atmega3290p -o ex1.elf ex1.c
This command compiles the ex1.c source file for a atmega3290p device and has the output written to ex1.elf, which may be used by your development environment.
If a hex file is required, for example, to load into a device programmer, then use the following command:
avr-objcopy -O ihex a.out exl.hex
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 and make utilities must be employed to achieve incremental builds (see 3.2.3 Multi-Step C Compilation).
Unless otherwise specified, an ELF file (this is called
a.out
without use of the -o
option) is produced as
the final output.
The intermediate files remain after compilation has
completed, but most other temporary files are deleted, unless you use the
-save-temps
option (see 3.6.5.5 Save-temps Option) which preserves all generated
files except the run-time start-up file. Note that some generated files can be in a
different directory than your project source files when building with an IDE (see also
3.6.2.3 O: Specify Output File).