Yahoo Groups archive

AVR-Chat

Index last updated: 2026-04-28 22:41 UTC

Message

Re: [AVR-Chat] can we use templates in Avr Gcc

2006-08-17 by Ned Konz

Naveen Koul wrote:

> can we use templates in avr gcc. 

Yes, but...

You'll have to write your own.

Forget about standard compliance, because...

The C++ standard library is not available, so you won't have the STL 
available. Nor the various support functions

You may have to write your own trivial global operator new and delete, 
if you're using any dynamic memory. Likewise for the unimplemented 
virtual method handler. These are below, in very simple form.

You may get unnecessary global constructors generated.

I've been writing my own templates, and have had excellent results with 
the code produced (especially by AVR-gcc v 4.2.0).

I've even done a couple of little programs for the RAM-less AVRs 
(ATTiny15L, for instance) and have been able to get by without needing RAM.

Some handy little things:

---------- inline.h

/// \brief Used on the declaration/definition of an inline function or 
method.
/// Tries to force the compiler to inline it, even without optimization 
being
/// active.
#define INLINE __attribute__((always_inline)) inline

---------- new.h

/*! \file new.h Stubs for global operator new, operator delete
  * #include "new.h"
  */
#ifndef INCLUDED_INCLUDE_NEW_H
#define INCLUDED_INCLUDE_NEW_H

// \brief define if you don't need ::new() and ::delete()
#define DONT_USE_NEW 1

#if !defined(DONT_USE_NEW)
extern void *operator new(size_t) throw();
#endif

extern void operator delete(void *);

extern "C" {
extern void __cxa_pure_virtual();       // pure virtual handler
}

#endif                          /* INCLUDED_INCLUDE_NEW_H */

---------- new.cpp

/*! \file new.cpp Implementation of global operator new,
  * operator delete, pure virtual trap
  */

extern "C" {
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
}

#include "new.h"

#if !defined(DONT_USE_NEW)

void *
operator new(size_t sz) throw()
{
     void * retval = malloc(sz);
     assert(retval != 0);
     return retval;
}

#endif

void
operator delete(void *p)
{
#if defined(DONT_USE_NEW)
     (void)p;
     abort();
#else
     free(p);
#endif
}

void
__cxa_pure_virtual()
{
     abort();
}



Enjoy,
-- 
Ned Konz
ned@bike-nomad.com
http://bike-nomad.com

Attachments

Move to quarantaine

This moves the raw source file on disk only. The archive index is not changed automatically, so you still need to run a manual refresh afterward.