Hi everybody,
a couple of months ago I started with AVR and c++. It's rather painful adventure, but now most of things seems to work. So I decided to share my little experience, maybe it will be useful for you.
First thing – setup. I use AVR Studio, which is almost working with c++. Almost, because you must manually in project->Configuration options->Custom options set instead of avr-gcc avr-c++.exe to compile any of your c++ files. Just changing the extension to cpp/hpp doesn't work. Remember that if you want to debug your application you need rather to turn off code optimization (-O0). In other case debugging is extremely hard thing to do and confusing. Final compilation can be done with any optimization options.
Next thing to do is to define new and delete operators:
#includevoid * operator new(size_t size); void operator delete(void * ptr);
and implementation:
void * operator new(size_t size) { return malloc(size); } void operator delete(void * ptr) { free(ptr); }
That's almost all. Almost because if you are using gcc 4.x and newer (I didn't check it with older versions) and you want to use templates, virtual inheritance and so on you must define some additional functions, which is not used now by compiler, but must be present to satisfy linker:
__extension__ typedef int __guard __attribute__((mode (__DI__))); extern "C" int __cxa_guard_acquire(__guard *); extern "C" void __cxa_guard_release (__guard *); extern "C" void __cxa_guard_abort (__guard *);
Please be sure to define these functions exactly as I showed, I other case gcc could crash during compilation (segmentation fault!), and for sure your program WILL BE NOT working.
Implementation is as follow (very important too):
int __cxa_guard_acquire(__guard *g) {return !*(char *)(g);}; void __cxa_guard_release (__guard *g) {*(char *)g = 1;}; void __cxa_guard_abort (__guard *) {};
And last thing, if you use pure virtual functions you must define another function:
extern "C" void __cxa_pure_virtual(void);
and implementation:
void __cxa_pure_virtual(void) {};
This function is never called in normal operation. The only time this function may get called is if the application calls a virtual function while the object is still being created, which gives undefined behavior. So implementation is not very important for us.
With all this things defined I was able to compile my c++ programs without any problems, and I wish the same to you.
Greetings,
Tomasz.