Embedded C++ on CC3200

"C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off." -Bjarne Stroustrup

C++ has a big advantage in embedded development and we still have full control about timings and memory footprint. There are a few things to consider in the embedded world, but if you do it right, you'll get a lot of advantages almost for free.

How to switch from C to C++ with a CC3200 Project

1. Prepare your header files

Declare every function that you want to use from a cpp file as extern "C"

#ifndef __header_H__
#define __header_H__

#ifdef __cplusplus
extern "C" {  
#endif

void someFunction(void);

#ifdef __cplusplus
}
#endif
#endif

2. Change the linker script

Add a section for static constructors.

    .init_array :
    {
        __init_array_start = .;
        KEEP (*(.init_array*))
        __init_array_end = .;
    } > SRAM

3. Call static constructors

Before the processor starts to execute main(), it has to construct
all static objects. This code has to be placed in the startup file befor
your processor jumps to 'main'.

    __asm("         ldr     r10, =__init_array_start\n"
    "       ldr     r11, =__init_array_end\n"
    "globals_init_loop: \n"
    "       cmp     r10,r11\n"
    "       bhs     done\n"
    "       ldr     r12, [r10], #4\n"
    "       blx     r12\n"
    "       b       globals_init_loop\n"
    "done: nop \n");

4. Create make rules Create a rule to compile .cpp files with your C++ compiler.
Add these flags to reduce your memory footprint.

CPPFLAGS= \  
    -ffunction-sections \
    --specs=nano.specs \
    -fdata-sections \
    -fno-exceptions \
    -fno-builtin \
    -std=c++0x \
    -fno-rtti \
    -mthumb \
    -flto

And I had to use these linker flags, too.

LDFLAGS= -gc-sections \  
         -static 

5. Custom new and delete operators

/*
 * Override C++ new/delete operators to reduce memory footprint
 */
void *operator new(size_t size) {  
    return malloc(size);
}

void *operator new[](size_t size) {  
    return malloc(size);
}

void operator delete(void *p) {  
    free(p);
}

void operator delete[](void *p) {  
    free(p);
}

These are the major changes. You will have to do some minor changes by your own. These are depending on your project. But now you should be able to compile your project with a C++ compiler.

Feel free to use our project as reference. WyLight Github Repository

The most interesting files are here:
Linker Script Startup File

If you want to use FreeRTOS task's, have a look at following files, too.
Task.h Task.cpp

comments powered by Disqus