5.3.1.1 Compiling a Single C++ File
The following is a simple C++ program. 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 ex2.cpp.
/* ex2.cpp */
#include <xc.h>
#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <string>
#include <algorithm>
#include <iterator>
#include <functional>
#include <numeric>
using namespace std;
//Device - Specific Configuration - bit settings
#pragma config FPLLMUL=MUL_20, FPLLIDIV=DIV_2, FPLLODIV=DIV_1
#pragma config FWDTEN=OFF
#pragma config POSCMOD=HS, FNOSC=PRIPLL, FPBDIV=DIV_8
template < class T >
inline void
print_elements(const T & coll, const char *optcstr = "") {
typename T::const_iterator pos;
std::cout << optcstr;
for (pos = coll.begin(); pos != coll.end(); ++pos) {
std::cout << *pos << ' ';
}
std::cout << std::endl;
}
template < class T >
inline void
insert_elements(T & coll, int first, int last) {
for (int i = first; i <= last; ++i) {
coll.insert(coll.end(), i);
}
}
int
main(void) {
//Direct stdout to UART 1 for use with the simulator
__XC_UART = 1;
deque<int>coll;
insert_elements(coll, 1, 9);
insert_elements(coll, 1, 9);
print_elements(coll, "on entry: ");
// sortelements
sort(coll.begin(), coll.end());
print_elements(coll, "sorted: ");
//sorted reverse
sort(coll.begin(), coll.end(), greater < int >());
print_elements(coll, "sorted >: ");
while (1);
}
The first line of the program includes the header file xc.h
, which
provides definitions for all Special Function Registers (SFRs) on the target device. The
second file of the program includes the header file, which provides the necessary
prototypes for the peripheral library.
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-g++ -mprocessor=32MX795F512L -Wl,--defsym=_min_heap_size=0xF000 -o ex2.elf ex2.cpp
The option -o ex2.elf
names the output executable file. This elf file
may be loaded into MPLAB X IDE.
If a hex file is required, for example, to load into a device programmer, then use the following command
xc32-bin2hex ex2.elf
This creates an Intel hex file named ex2.hex
.