5.3.2 Compiling Multiple C and C++ Files

This section demonstrates how to compile and link multiple C and C++ files in a single step.

File 1

/* main.cpp */
#include <xc.h>
#include <iostream>
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
// add() must have C linkage
extern "C" {
    extern unsigned int add(unsigned int a, unsigned int b);
}
int main(void) {
    int myvalue = 6;
    //Direct stdout to UART 1 for use with the simulator
    __XC_UART = 1;
    std::cout << "original value: " << myvalue << endl;
    myvalue = add(myvalue, 3);
    std::cout << "new value:
    while (1);
}

File 2

/* ex3.c */
unsigned int
add(unsigned int a, unsigned int b)
{
return(a+b);
}

Compile both files by typing the following at the prompt:

xc32-g++ -mprocessor=32MX795F512L -o ex3.elf main.cpp ex3.c

The command compiles the modules main.cpp and ex3.c. The compiled modules are linked with the compiler libraries for C++ and the executable file ex3.elf is created.

Note: Use the xc32-g++ driver (as opposed to the xc32-gcc driver) in order to link the project with the C++ support libraries necessary for the C++ source file in the project.