6.2.2 Single-Step Compilation
A single command-line can be used to compile one file or multiple files.
Compiling a Single File
This section demonstrates how to compile and link a single file. For the purpose of this discussion, it is assumed the compiler is installed in the standard directory location and that your PATH or other environment variables are set up in such a way that the full compiler path need not be specified when you run the compiler.
The following is a simple C program that adds two numbers.
Create the following program with any text editor and save it as
ex1.c
.
#include <xc.h>
int main(void);
unsigned int Add(unsigned int a, unsigned int b);
unsigned int x, y, z;
int main(void)
{
x = 2;
y = 5;
z = Add(x,y);
return 0;
}
unsigned int Add(unsigned int a, unsigned int b)
{
return(a+b);
}
The first line of the program includes the header file
xc.h
, which will include the appropriate header files that provides
definitions for all special function registers on the target device. For more
information on header files, see the 7.2 Device Header Files section.
Compile the program by typing the following at the prompt in your favorite terminal.
xc-dsc-gcc -mcpu=30f2010 -T
p30f2010.gld -o ex1.elf ex1.c
The command-line option -o ex1.elf
names the output
executable file (if the -o
option is not specified, then the output
file is named a.out
). The executable file 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:
xc-dsc-bin2hex
ex1.elf
This creates an Intel hex file named ex1.hex
.
Compiling Multiple Files
Move the Add()
function into a file called
add.c
to demonstrate the use of multiple files in an application.
That is:
/* File 1 */
/* ex1.c */
#include <xc.h>
int main(void);
unsigned int Add(unsigned int a, unsigned int b);
unsigned int x, y, z;
int main(void)
{
x = 2;
y = 5;
z = Add(x,y);
return 0;
}
/* File 2 */
/* add.c */
#include <xc.h>
unsigned int Add(unsigned int a, unsigned int b)
{
return(a+b);
}
Compile both files in the one command by typing the following in your terminal program.
xc-dsc-gcc -mcpu=30f2010 -T
p30f2010.gld -o ex1.elf ex1.c add.c
This command compiles the modules ex1.c
and
add.c
. The compiled modules are linked with the compiler libraries
and the executable file ex1.elf
is created.