Author Topic: Which is better for embedded work: C or C++?  (Read 42252 times)

0 Members and 1 Guest are viewing this topic.

Offline vvanders

  • Regular Contributor
  • *
  • Posts: 124
Re: Which is better for embedded work: C or C++?
« Reply #75 on: June 29, 2013, 11:03:09 pm »
However, C++ doesn't require dynamic allocation any more than C does, and whichever style of allocation you prefer will work in both language.

This right here. There's a lot of straw man arguments being thrown around about constructors, they're no different than init functions. The issue becomes with statically declared objects that don't have an well defined initialization order. Hence the need to separate out any code that cares about sequencing vs default value initialization.

That was exactly my point. You end up with two lots of init code and have to decide which goes in the constructor and which goes in the init() method you call later. Why bother? Just put it all in the init() method and be done with it.
Nope you're missing the point:

The issue becomes with statically declared objects that don't have an well defined initialization order.

Proper usage of C++ you'd use a prefixed pooled allocator or a singleton which doesn't have this issue and you'd have a single constructor. The problem exists with the fact that initialization order of static globals isn't defined, not with constructors themselves.

Again, I never said that C++ needs dynamic allocation, I was only pointing out to the people advocating it why it's such a really, really bad idea. More generally you have to know all this stuff in order to use C++ safely, and it is evident that some of the posters here don't, demonstrating my point.
The only person advocating dynamic allocation is you.

Every other poster who touches on it mentions using a fixed allocator. Just because you see a the "new" keyword does not mean that dynamic allocation happens. Operator overloading or placement new can both return addresses that are a fixed allocation.
 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1289
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #76 on: June 30, 2013, 12:04:10 pm »
I could write clever responses yet again but it starts to look like this thread is devolving into uselessness. Let my remaining comment therefore be that the doubters should try C++ for themselves before judging it. But that is probably useless as well. As they say, if there's a will, there's a way and vice versa. If you have made up your minds that C++ is useless in embedded systems then surprise, that is what you are going to find out by making a half hearted attempt just to confirm your doubts.

So for my part, let's agree do disagree and to each his own. My parting shot is that not one of the bogeys you pull out of the closet has bitten me yet and i don't expect them to. Maybe that is due to the 25 years i have had to practice applying C++, maybe not. The main this is, as noted here, to not suck at using your selected tools. That includes understanding when not to use all the clever features. Remember that in its time C was also criticized as the language that lets you shoot yourself in the foot with perfect ease. So should we therefore all go back to using assembler? I think not.
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline millerb

  • Regular Contributor
  • *
  • Posts: 71
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #77 on: June 30, 2013, 12:19:53 pm »
Quote
Maybe that is due to the 25 years i have had to practice applying C++

That's a key point. It takes years to become proficient with C++ and that puts it more within the domain of folks who spend most of their time writing software.
 

Offline mrflibble

  • Super Contributor
  • ***
  • Posts: 2051
  • Country: nl
Re: Which is better for embedded work: C or C++?
« Reply #78 on: June 30, 2013, 12:51:27 pm »
I could write clever responses yet again but it starts to look like this thread is devolving into uselessness.

No reason for it to devolve into uselessness. Just because one poster has been bitten by Bozo the C++ clown in his formative years doesn't suddenly invalidate the entire thread. In fact, many useful points have been made. So lets just concentrate on the useful stuff and kindly ignore the <omg_but_the_random_order> stuff because yes yes I read and understood it the first time.

Quote
The main this is, as noted here, to not suck at using your selected tools. That includes understanding when not to use all the clever features. Remember that in its time C was also criticized as the language that lets you shoot yourself in the foot with perfect ease. So should we therefore all go back to using assembler? I think not.

Indeed. I also noted quite a few similarities between this and the good old "asm vs C" debate. Some of it is rational, and quite a bit of it is just misguided waffle. And just as with that old debate here you can just keep the insightful points and incorporate that into your work, while ignoring said misguided waffle. Works for me. ;)
 

Offline Rufus

  • Super Contributor
  • ***
  • Posts: 2095
Re: Which is better for embedded work: C or C++?
« Reply #79 on: June 30, 2013, 01:41:45 pm »
Let my remaining comment therefore be that the doubters should try C++ for themselves before judging it.

If you don't 'get' OOP then you don't see any benefit using a language with support for it so you won't justify any sacrifices required to use that language even if they turn out to be trivial.
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 26906
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #80 on: June 30, 2013, 02:10:29 pm »
Actually besides OO (which can also be done with plain C) C++ offers many nice features (like passing by reference, dynamic sized arrays) which make programs less prone to errors with pointers or allocation mistakes.
« Last Edit: June 30, 2013, 05:17:07 pm by nctnico »
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline vvanders

  • Regular Contributor
  • *
  • Posts: 124
Re: Which is better for embedded work: C or C++?
« Reply #81 on: July 01, 2013, 12:37:38 am »
But if you don't statically declare you are into the dynamic allocation minefield. I understand you are trying to claim that allocating only once and never freeing is somehow safe, but it isn't.

Not what I'm saying at all. Proper usage if placement new or a pooled allocator(which can declare a static memory size) doesn't leave the object in an uninitialized state. You can still call destructors and get all the C++ goodness. Also static variables in functions do have a specified initialization order and are perfectly safe.

Using "new" usually allocates at runtime. As you point out it doesn't always work that way, but once again you are into the realms of knowing exactly how to safely use all these features and ensure that the compiler does what you think it is doing. That was my original point - it's possible, but not wise. I defer to the master on this one:

Quote
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

— Brian Kernighan

Anything large should be statically allocated. The stack should only be used for return addresses and small automatic variables. You will note that the standard I/O functions like sprintf don't use malloc on many embedded architectures such as AVR, although they are still dangerous and must be handled with care since they can use up stack. I've spent quite some time verifying that using sprintf and associated functions won't use any heap allocation and won't use more than a minimal amount of stack space.

I'm not disagreeing at all, in all the cases I've listed things are statically allocated. These things are *not* complex, they're embedded C++ 101 for anyone who wants to write performance oriented code.
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 26906
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #82 on: July 01, 2013, 01:18:43 am »
IMHO everything which is allocated and never freed is static. The only difference is that the allocation occurs at initialisation time instead of compile time. Some products can have allocation needs based on a configuration. One of the biggest embedded projects (without OS) I worked on used allocation at initialisation. My part was an ISDN30 protocol stack which could either be the network or client side depending on the configuration. The whole thing was OO in plain C to allow for allocating the data structures and linking the modules when the stack was initialised. Was this a bad thing? No, everything was perfectly predictable.

So IMHO you'd be perfectly fine to instantiate C++ objects using 'new' in a microcontroller during initialisation. Just as long as you don't free them and check the amount of heap memory.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline Jeroen3

  • Super Contributor
  • ***
  • Posts: 4078
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: Which is better for embedded work: C or C++?
« Reply #83 on: July 01, 2013, 10:10:03 pm »
But, make sure you check your stack & heap sizes. Strange things happen when you outrun them!
Memory problems are hard to debug if you cannot step instructions and read memory, in-system.

Ans for starters C++ provides more easy ways to crash your system then C does.

Something else,
I'll do some benchmarks between the C and C++ compiler running my (I think) highly efficient raw 32bit ringbuffer.
Maybe port it to C++ as well and see how it goes.
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 26906
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #84 on: July 01, 2013, 11:34:47 pm »
But, make sure you check your stack & heap sizes. Strange things happen when you outrun them!
Memory problems are hard to debug if you cannot step instructions and read memory, in-system.
Which is why my bigger projects have runtime stack and heap checking and if available I make the fault interrupts print some meaningfull data over the serial port. Another 'trick' I use is compartmentalisation so errors don't cascade into a crash in an unrelated piece of code. And its simple to implement: do a range check on input values / pointer ranges.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline cthree

  • Frequent Contributor
  • **
  • Posts: 258
  • Country: ca
Re: Which is better for embedded work: C or C++?
« Reply #85 on: July 02, 2013, 04:43:35 am »
I wrote some C++ yesterday. It was meh.
 

Offline andyturkTopic starter

  • Frequent Contributor
  • **
  • Posts: 895
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #86 on: July 02, 2013, 06:31:11 am »
I wrote some C++ yesterday. It was meh.
Which was was "meh"? The language or your code? Let us be the judge... post it! Give mojo-chan something to sink his teeth into!  >:D

Here, I'll start:

Code: [Select]
/**
 * @file    flipbuffer.h
 * @brief   Fixed-length read/write buffer class
 *
 * @details The FlipBuffer class manages a fixed-sized block of memory
 *          that can be either read from or written to. It's designed to
 *          eliminate unecessary copying when the data is passed from the
 *          producer to the consumer. First, the producer fills the buffer
 *          with data. The flip method must be called before the data in
 *          the buffer can be used.
 */

namespace akt {
  template<class T> class FlipBuffer {
  protected:
    T *storage;
    unsigned cap, pos, lim;

  public:
  FlipBuffer() : storage(0), cap(0), pos(0), lim(0) {}
  FlipBuffer(T *s, unsigned c) : storage(s), cap(c), pos(0), lim(c) {}
    unsigned capacity() const {return cap;}
    unsigned position() const {return pos;}
    unsigned tell() const {return pos;}
    unsigned limit() const {return lim;}
    unsigned remaining() const {return lim - pos;}

    T &operator   *() const {return storage  [pos];}
    operator    T *() const {return storage + pos;}
    operator void *() const {return storage + pos;}

    void init(T *s, unsigned c) {
      storage = s;
      lim = cap = c;
      pos = 0;
    }

    void limit(unsigned l) {
      assert(l <= cap);
      lim = l;
    }

    void reset(unsigned l=0) {
      assert(l <= cap);
      pos = 0;
      lim = (l == 0) ? cap : l;
    }

    void flip() {
      lim = pos;
      pos = 0;
    }

    void rewind(unsigned p = 0) {
      pos = p;
    }

    void seek(unsigned p) {
      assert(p <= lim);
      pos = p;
    }
   
    T operator++() { // prefix form
      assert(pos < lim-1);
      return storage[++pos];
    }

    T operator++(int dummy) { // postfix form
      assert(pos < lim);
      return storage[pos++];
    }

    T &operator[](int offset) const {
      assert(pos+offset <= lim);
      return storage[pos+offset];
    }

    FlipBuffer &operator+=(int offset) {
      assert(pos+offset <= lim);
      pos += offset;
      return *this;
    }
   
    void /*__attribute__ ((deprecated))*/ skip(int offset) {
      assert(pos+offset <= lim);
      pos += offset;
    }
 
    FlipBuffer &operator<<(T x) {
      assert(pos+sizeof(x) <= lim);
      storage[pos++] = x;
      return *this;
    }

    FlipBuffer &operator>>(T &x) {
      assert(pos+sizeof(x) <= lim);
      x = storage[pos++];
      return *this;
    }

    FlipBuffer &read(T *p, unsigned len) {
      assert(pos+len <= lim);
      memcpy(p, storage+pos, len);
      pos += len;
      return *this;
    }

    FlipBuffer &write(const T *p, unsigned len) {
      assert(pos+len <= lim);
      memcpy(storage+pos, p, len);
      pos += len;
      return *this;
    }
  };
  template<class T, unsigned S> class SizedFlipBuffer : public FlipBuffer<T> {
  protected:
    T data[S];
  public:
    SizedFlipBuffer() : FlipBuffer<T>(data, S) {}
  };
};
 

Offline ElektroQuark

  • Supporter
  • ****
  • Posts: 1244
  • Country: es
    • ElektroQuark
Re: Which is better for embedded work: C or C++?
« Reply #87 on: July 02, 2013, 08:02:55 am »
What's "meh"?  :-[
Sorry, I'm following this thread with interest but i'm not a native English speaker.

Offline millerb

  • Regular Contributor
  • *
  • Posts: 71
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #88 on: July 02, 2013, 08:05:37 am »
What's "meh"?  :-[
Sorry, I'm following this thread with interest but i'm not a native English speaker.

"meh" -> uninteresting.
 

Offline ElektroQuark

  • Supporter
  • ****
  • Posts: 1244
  • Country: es
    • ElektroQuark
Re: Which is better for embedded work: C or C++?
« Reply #89 on: July 02, 2013, 08:08:47 am »
Thank you. It's an informal word, I suppose.

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1289
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #90 on: July 02, 2013, 12:51:00 pm »
Let us be the judge... post it! Give mojo-chan something to sink his teeth into!  >:D
OK, i'll bite. Unfortunately mine is too long to post as text in the message so it is attached.
This is a functional camera dolly controller with motion control (movement along a track and X-Y panning) and camera control. The sequence of actions is programmed as a simple linked list. Multiple lists are  persistable in the EEPROM for later retrieval and execution. Some of the X-Y servo code is still incomplete in this version.
It is a .PDE file i.e. an Arduino project, so you can see that a limited environment is not a problem.
I posted the whole thing but the beef is the linked list class hierarchy towards the end. You'll find it easily although the comments are in Finnish. Sorry about that but it was done for the local user base. Also, this is a quick&dirty job with no safeguards against memory exhaustion because the consequences of that are less than dramatic. Whatever can be created can be run, stored and retrieved. The sequences are usually short(ish) and there are optimizations to minimize memroy consumption (programmable repeat sequences).
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1289
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #91 on: July 02, 2013, 03:15:47 pm »
By all means troll here as well. Oh, sorry - you did already?
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline AlfBaz

  • Super Contributor
  • ***
  • Posts: 2184
  • Country: au
Re: Which is better for embedded work: C or C++?
« Reply #92 on: July 02, 2013, 03:32:40 pm »
The funny thing about all this is the more time you spend programming in C the more tricks you come up with to modularise/objectify your code in an attempt to maintain, easily upgrade and understand you code as time passes. Eventually you find you are trying to emulate what C++ does natively.

If any of the constructs previously talked about are a concern in a resource limited environment, there's nothing stopping you from writing bog standard C code with a C++ compiler (pragma's not withstanding)
 

Offline jerry507

  • Regular Contributor
  • *
  • Posts: 247
Re: Which is better for embedded work: C or C++?
« Reply #93 on: July 04, 2013, 06:22:28 am »
Arguably if your code is that complex you are doing it wrong anyway. I have huge projects written in C and don't have any issues coming back to them after a decade for maintenance or upgrades.

Wow, backhanded insults. Classy.

I have written large projects in both C and C++ on both embedded and desktop platforms. But if you're coming back to a project a decade later and it all makes sense, you must have a very stable coding style. That tells me you're not learning anything new and evolving naturally. That seems to jive well with your opinions expressed in this thread. I've also seen plenty of large projects written by people who think OO is useless and they're rarely easy to upgrade or maintain. They usually benefit from an unusually good amount of definition at the start, and how often does that realistically happen? When you start using the word large as an adjective then we're long past talking about optimized and minimalist and into the realm of easy to understand, easy to maintain and easy to extend.

I like constructors. They let me transfer a chunk of code that I honestly don't care about to a different spot where it's out of the way in a nice, standard, portable way. My large project has enough complexity to it that I can do without arbitrary language restrictions.
 

Offline cthree

  • Frequent Contributor
  • **
  • Posts: 258
  • Country: ca
Re: Which is better for embedded work: C or C++?
« Reply #94 on: July 04, 2013, 01:03:56 pm »
Arguably if your code is that complex you are doing it wrong anyway. I have huge projects written in C and don't have any issues coming back to them after a decade for maintenance or upgrades.

Wow, backhanded insults. Classy.

I have written large projects in both C and C++ on both embedded and desktop platforms. But if you're coming back to a project a decade later and it all makes sense, you must have a very stable coding style. That tells me you're not learning anything new and evolving naturally. That seems to jive well with your opinions expressed in this thread. I've also seen plenty of large projects written by people who think OO is useless and they're rarely easy to upgrade or maintain. They usually benefit from an unusually good amount of definition at the start, and how often does that realistically happen? When you start using the word large as an adjective then we're long past talking about optimized and minimalist and into the realm of easy to understand, easy to maintain and easy to extend.

I like constructors. They let me transfer a chunk of code that I honestly don't care about to a different spot where it's out of the way in a nice, standard, portable way. My large project has enough complexity to it that I can do without arbitrary language restrictions.

Pot, kettle
 

Offline PuterGeek

  • Regular Contributor
  • *
  • Posts: 88
  • Country: us
    • SolutionsPLUS engineering
Re: Which is better for embedded work: C or C++?
« Reply #95 on: July 04, 2013, 09:07:39 pm »
Like all things involving programming, I am sure the programmer's experience and training are the predominant factor in code quality (see http://www.embedded.com/design/prototyping-and-development/4008870/Embedded-systems-programmers-worldwide-earn-failing-grades-in-C). I have seen C used to essentially write assembly language code as well as something akin to Fortran (a Fortran program converted to C). I've seen incomprehensible "expert" code in many languages that doesn't comply to any known coding standard.

A huge part of the problem is the range that embedded systems cover. All of the following are considered embedded systems in industry:
  • simple single board device with a small MCU and a little interface circuitry (e.g., a simple 8051 MCU dev board)
  • complex single board device with advanced MCU and lots of interface circuitry (e.g., an ARM dev board with LCD, CAN, RS-232, etc.)
  • commercial of the shelf (COTS) backplane based system with multiple boards (e.g., PXI system with advanced I/O boards)
  • complex device running Linux (e.g. Tivo)
  • complex device running WinCE (e.g. numerous test instruments)
  • complex device running Windows Embedded (e.g., kiosk)
  • industrial PC running full Windows (e.g., cash register)
There are enumerable examples of each and language choices increase with complexity. The 8051 only supports assembly and C. ARM MCUs can easily be developed in assembly, C and C++ with ADA or other languages requiring slightly more effort. Linux based systems and up support virtually anything you might want to use.

I suspect the OP was targeting the first two and possibly part of the third which is the more "traditional" definition of embedded. With that in mind, and rather than continuing the subjective arguments on which language is better, does anyone know of objective evidence showing C or C++ is superior?

A quick Google found many subjective hits but objective ones were few. I also searched embedded.com (highly recommended by the way). Here are a few interesting things I found although I'm not sure any of these are truly subjective but do address objections to C++:
www.eetindia.co.in/ARTICLES/.../EEIOL_1998FEB02_EMS_TA.pdf?
http://www.microcontrollercentral.com/author.asp?section_id=2379&doc_id=258378
http://www.embedded.com/electronics-blogs/programming-pointers/4024635/Moving-to-higher-ground
http://www.embedded.com/electronics-blogs/programming-pointers/4027504/Poor-reasons-for-rejecting-C-
http://www.embedded.com/electronics-blogs/programming-pointers/4396295/Impure-thoughts
http://www.embedded.com/electronics-blogs/programming-pointers/4026943/Better-even-at-the-lowest-levels
http://www.drdobbs.com/cpp/why-code-in-c-anymore/240149452
http://www.eventhelix.com/realtimemantra/basics/ComparingCPPAndCPerformance.htm
http://www.eventhelix.com/realtimemantra/basics/ComparingCPPAndCPerformance2.htm
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 26906
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #96 on: July 04, 2013, 11:10:33 pm »
I've seen very experienced programmers F*** up larger projects due to lack of a systematic method to design the structure of the software. There is no language which helps to prevent that except for 'you're fired'.  :-DD
« Last Edit: July 04, 2013, 11:18:17 pm by nctnico »
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Re: Which is better for embedded work: C or C++?
« Reply #97 on: July 05, 2013, 02:20:22 am »
Little OT

About C, is there any software that can say how mistra"misra" rules are satisfied by the piece of code you have written ?
Something OpenSource or Commercial ?
« Last Edit: July 05, 2013, 02:00:36 pm by legacy »
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Re: Which is better for embedded work: C or C++?
« Reply #98 on: July 05, 2013, 02:31:24 am »
What do you think about

- "Design Patterns for Embedded Systems in C: An Embedded Software Engineering" book (click)
- "Design Patterns: Elements of Reusable Object-Oriented Software" book (click)
 

Offline mrflibble

  • Super Contributor
  • ***
  • Posts: 2051
  • Country: nl
Re: Which is better for embedded work: C or C++?
« Reply #99 on: July 05, 2013, 01:44:20 pm »
About C, is there any software that can say how "mistra" rules are satisfied by the piece of code you have written ?
By mistra I take it you mean misra?

Quote
Something OpenSource or Commercial ?
You can always use the list of tools as a starting point. And when too expensive, google for equivalents that fit your requirements & budget.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf