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

0 Members and 2 Guests are viewing this topic.

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 892
  • Country: us
Which is better for embedded work: C or C++?
« on: May 21, 2013, 01:37:21 am »
There have been a couple of interesting discussions here on software topics. Assembly vs C is one, and the ISR discussion is interesting too.

So, what about C vs C++? The question is moot for rinky-dink microcontrollers that don't have a C++ compiler, but for modern "reasonable" architectures (e.g., ARM, MSP430) it's an interesting choice. Most embedded code is straight C, but there's a growing number of C++ folks in the mcu world.

Given a choice, I'll go with C++ in a heartbeat. A major reason is that C++ makes structure initialization much more rational with constructors. C++ objects are implemented in a way that's similar to adding a compiler-managed parameter block to each function, avoiding the need to have so many static variables. Namespaces, templates, virtual functions and references only add to the C++ win.

What say you?
 

Offline jebcom

  • Regular Contributor
  • *
  • Posts: 81
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #1 on: May 21, 2013, 01:40:44 am »
I say it depends on:
1. How valuable object orientation will be to the system.
2. Whether you have resources for the overhead of C++. The executable can be bloated.
For a simple system, I'd go with C, but that's just my opinion. If it gets very involved  you probably want OO.
 

Offline Rufus

  • Super Contributor
  • ***
  • Posts: 2094
Re: Which is better for embedded work: C or C++?
« Reply #2 on: May 21, 2013, 02:11:33 am »
What say you?

I would say please don't lest we get pages of opinion like the assembler thread which verged on trolling.
Pages of opinion are not that interesting because, like arseholes everyone has one.
 

Offline snoopy

  • Frequent Contributor
  • **
  • Posts: 644
  • Country: au
    • Analog Precision
Re: Which is better for embedded work: C or C++?
« Reply #3 on: May 21, 2013, 02:23:56 am »
I use C++ and Visual DSP for an analog devices Sharc DSP. Could never go back to using C after using C++. Much more structured programming and reusable objects etc. Also the Standard Template library comes in handy even with embedded apps ;)

As for bloat-wear I don't think you will write better assembler code than an optimizing C/C++ compiler can especially for a DSP ;)

regards
david
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #4 on: May 21, 2013, 01:17:55 pm »
IMHO it is a good idea. The biggest problem I see with C is that it is easy to overlook a pointer or create a buffer overflow. When used well C++ can avoid these pitfalls. OTOH it doesn't hurt to look at other languages. I plan to experiment a bit with embedded Lua. Maybe even create a relatively cheap box with some I/O with which people can experiment or use it as a controller.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline andete

  • Contributor
  • Posts: 19
  • Country: be
  • famous for its killer edible poets
Re: Which is better for embedded work: C or C++?
« Reply #5 on: May 21, 2013, 01:24:24 pm »
For small micro-controllers I use C++ but I only use namespaces and references and very rarely some templates. No classes or fancy object-oriented stuff. (I'm a functional programming style person)

Just using namespaces allows organizing code more which improves readability and avoids ridiculously long function and variable names.

Using references allows for more defensive coding making clear at compile time that null-pointers are not allowed for a certain code path.
 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 892
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #6 on: May 21, 2013, 02:52:06 pm »
Pages of opinion are not that interesting because, like arseholes everyone has one.
Some of the stuff in those other threads was pretty good. And besides, any engineer worth his salt should have enough opinion for two arseholes.  :rant:
 

Offline AlfBaz

  • Super Contributor
  • ***
  • Posts: 2009
  • Country: au
Re: Which is better for embedded work: C or C++?
« Reply #7 on: May 21, 2013, 04:15:24 pm »
... And besides, any engineer worth his salt should have enough opinion for two arseholes.  :rant:
:-DD
Any engineer worth his salt shouldn't need fifty thousand lines of compiler generated code to prevent him from using a null pointer!
We should all graduate to EE++ to stop us from reversing polarities in our circuits :)
 

Offline mgronber

  • Contributor
  • Posts: 11
Re: Which is better for embedded work: C or C++?
« Reply #8 on: May 21, 2013, 04:24:30 pm »
2. Whether you have resources for the overhead of C++.

What overhead? With C++ you pay only for the features that you use and you get many nice features for free. The features that you have to pay for are not free in C either if you need such functionality.

It is a no-brainer. I choose C++.
 

Offline kfitch42

  • Frequent Contributor
  • **
  • Posts: 300
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #9 on: May 21, 2013, 04:45:59 pm »
What overhead? With C++ you pay only for the features that you use and you get many nice features for free. The features that you have to pay for are not free in C either if you need such functionality.

It is a no-brainer. I choose C++.

You can  turn off most features in most C++ compilers, but often that takes effort. e.g. you may need to add a few command line options like:
-fno-rtti -fno-exceptions -fno-threadsafe-statics ...

The 'problem' with C++ is that it is VERY easy to use a feature that has tremendous implications for things like code size. e.g. templates, virtual functions...

Basically you need to know C++ very well in order to know how to understand the relationship between the code that is written and the code that is generated. That way you can know how to fix problems by not using certain features. e.g. Tweaking a class to make it POD (Plain Old Data) ...

In large part this debate depends on your definition of 'embedded'. For some people embedded is an ARM running into the hundreds of MHz with 10s to 100s of MBs of RAM. In those cases the 'bloat' of C++ might be well worth the ability to use 3rd party C++ libraries and the features of C++ that make it work better on large applications.

But, in a more constrained definition of embedded 10s of MHz to a few MB of RAM, the benefits of C++ become a bit more dubious. Get down to microcontrollers, and the debate becomes about C vs Assembly instead of C vs C++.

That all being said, personally, if I have a choice, I use C for things that need the speed (or need to touch hardware), and Python for everything else.
 

Offline mgronber

  • Contributor
  • Posts: 11
Re: Which is better for embedded work: C or C++?
« Reply #10 on: May 21, 2013, 05:39:20 pm »
The 'problem' with C++ is that it is VERY easy to use a feature that has tremendous implications for things like code size. e.g. templates, virtual functions...

We were talking about engineers worth their salt. Right? :)

Quote
Basically you need to know C++ very well in order to know how to understand the relationship between the code that is written and the code that is generated.

Or at least you need to be observant how the code size changes between builds so that accidental bloat can be detected as soon as possible. This applies to plain C too.

Quote
Get down to microcontrollers, and the debate becomes about C vs Assembly instead of C vs C++.

I agree. However, I don't see much reason to use C instead of C++ presuming that there is a proper C++ compiler available. The real question is which features of C++ should be used and which should be avoided.
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #11 on: May 21, 2013, 06:28:27 pm »
I agree. However, I don't see much reason to use C instead of C++ presuming that there is a proper C++ compiler available. The real question is which features of C++ should be used and which should be avoided.
The answer to that question is: the features which make the end result too expensive. For low volume products the development costs are the most significant so using a $20 controller instead of a $1 controller may be perfectly justifiable.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline kfitch42

  • Frequent Contributor
  • **
  • Posts: 300
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #12 on: May 21, 2013, 07:42:41 pm »
I agree. However, I don't see much reason to use C instead of C++ presuming that there is a proper C++ compiler available. The real question is which features of C++ should be used and which should be avoided.

What I was (indirectly) getting at in my previous post was that by using C you don't need to spend time evaluating the impact of each feature ... and which features are used by 3rd party tools/libraries... This can actually be a benefit in the scenario where schedule is one of your biggest constraints. Then again, when schedule is your biggest constraint, using whatever the dev team is familiar/comfortable with is probably best ... even if its a mixture of BrainFsck and Erlang :)
 

Online ejeffrey

  • Super Contributor
  • ***
  • Posts: 1989
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #13 on: May 21, 2013, 10:55:31 pm »
C++.  In C++ you don't pay for features you don't use (and it is easy to avoid them!).  At a minimum, you can use C++ as "super-C" with better namespace control (by using non-virtual member functions or namespaces), usable const, overloaded methods, and default arguments.  All of those features are essentially free, they make your code easier to develop, easier to read, and less buggy.  That leaves you the option of using additional features if you need them.  In particular, simple inheritance with virtual methods does add some overhead, no more (and often less) than if you implemented the same in C with explicit dispatch tables.

Templates, exceptions, and RTTI are features more likely to cause unacceptable overhead, but you can always just not use them, or you can use them carefully.

The argument that you might accidentally do something that causes your executable to double in size is not really credible.  Sure it might happen, but that is usually because you were saving a lot of time compared to doing something the hard way in C.  If you have to go back and fix it, you are usually not going to be much worse than if you had done things the hard way the first time.

Also, it is certainly possible to accidentally create bloat in C programs.  Allocating large arrays on the stack, Passing/returning structures by value, excessive inlining all spring to mind.

C++ traditionally lacked good compilers, especially in the embedded world.  In particular, there used to be a lot of embedded C++ compilers didn't achieve the promise of "no overhead for features you don't use", especially with exceptions.  If the C++ compiler for your platform sucks, that is a great reason to stick with C.  Otherwise, C++ really has no downsides. 
 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 892
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #14 on: May 22, 2013, 03:46:45 am »
The 'problem' with C++ is that it is VERY easy to use a feature that has tremendous implications for things like code size. e.g. templates, virtual functions...
Virtual functions don't cost very much... a little bit of code space for the vtables and a RAM pointer per instance for the vptr.  The thing is, if you need something like virtual functions, there's really no more efficient way to do it.

Templates, on the other hand, can get expensive quickly if you put a lot of method implementations in the template. If you move most of your methods into a base class, then it's not too bad.

Quote
[...] in a more constrained definition of embedded 10s of MHz to a few MB of RAM, the benefits of C++ become a bit more dubious. Get down to microcontrollers, and the debate becomes about C vs Assembly instead of C vs C++.
I'm using C++ (templates, virtual functions, and even multiple inheritance!) on a project with 128K of code space and 10K of RAM. Seems to be working out so far.
 

Offline mikeselectricstuff

  • Super Contributor
  • ***
  • Posts: 12041
  • Country: gb
    • Mike's Electric Stuff
Re: Which is better for embedded work: C or C++?
« Reply #15 on: May 22, 2013, 08:53:01 am »
The answer to that question is: the features which make the end result too expensive. For low volume products the development costs are the most significant so using a $20 controller instead of a $1 controller may be perfectly justifiable.
True, but larger code size will generally also mean higher power consumption, which may be an issue in low-power systems.

I don't know a great deal about C++, but you really want to avoid anything that uses dynamic memory allocation (or more strictly speaking de-allocation)  in an embedded system, as it's very hard to test to verify that it will never run out or become too fragmented to work at some point.
Youtube channel:Taking wierd stuff apart. Very apart.
Mike's Electric Stuff: High voltage, vintage electronics etc.
Day Job: Mostly LEDs
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #16 on: May 22, 2013, 11:10:17 am »
I have used dynamically linked lists as dynamic memory before. It works like a charm but you have to allocate / deallocate carefully. C++ can solve those problems.

My software usually is organised as several processes with very little global variables. If there is need for memory then the stack is the source of it. When a process starts the stack is as good as empty and when its exits it leaves the stack empty. If you apply the same mechanism with C++ then memory never gets full or fragmented. Things get interesting when you need buffers to be available for a longer period. In that case you'll need to make sure only a limited number of buffers can exist and that they are always cleaned up at some point. With carefull planning you can prevent memory from fragmenting and C++ makes that easier.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline mikeselectricstuff

  • Super Contributor
  • ***
  • Posts: 12041
  • Country: gb
    • Mike's Electric Stuff
Re: Which is better for embedded work: C or C++?
« Reply #17 on: May 22, 2013, 12:09:51 pm »
Things get interesting when you need buffers to be available for a longer period. In that case you'll need to make sure only a limited number of buffers can exist and that they are always cleaned up at some point.
..or never cleaned up - i.e. you allocate everything that will ever need allocating, assuming you have room to do that.
The main issue is not so much the actual usage, but testing/convincing yourself that it will never run out in service.
 
Youtube channel:Taking wierd stuff apart. Very apart.
Mike's Electric Stuff: High voltage, vintage electronics etc.
Day Job: Mostly LEDs
 

Online HackedFridgeMagnet

  • Super Contributor
  • ***
  • Posts: 1938
  • Country: au
Re: Which is better for embedded work: C or C++?
« Reply #18 on: May 22, 2013, 12:47:26 pm »
Quote
The main issue is not so much the actual usage, but testing/convincing yourself that it will never run out in service.
I realise that it depends on your application but for every app i've ever been involved with it is not that hard.
Assuming your watchdog is working, 99% certainty that the uptime is months has been good enough.
To get to something like this reliability on memory deallocation is fairly easy.
I can't remember ever having a serious memory leak problem. [edit. except once in objective c where I really didn't understand the system at all ]
Look at your code, test your code, use templates if you can, pass references, but watch sharing data between threads etc.
« Last Edit: May 22, 2013, 12:49:24 pm by HackedFridgeMagnet »
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #19 on: May 22, 2013, 12:50:11 pm »
There are two simple solutions: checking the space left of the heap is not diffcult because an allocation will fail when the system runs out of memory (which may cause a... whatever is suitable). Checking the stack is also possible. I usually do this by sampling the stack pointer in the timer interrupt. Then I test the stack pointer against the end of the data memory. If the stack pointer is in the data area things went wrong. I also have a command which shows me the lowest stack pointer which (after running for a while) shows the maximum stack usage.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline kfitch42

  • Frequent Contributor
  • **
  • Posts: 300
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #20 on: May 22, 2013, 02:51:18 pm »
..or never cleaned up - i.e. you allocate everything that will ever need allocating, assuming you have room to do that.
The main issue is not so much the actual usage, but testing/convincing yourself that it will never run out in service.
Whenever possible I like to design a system to start out in the worst case scenario. It makes testing much easier.  e.g. What if your input queue fills up at the same time that your output queue fills up at the same time that EVERY interrupt pin triggers. Having fixed size preallocated queues makes this test case possible, if those queues grow indefinitely, when do you give up testing? 10 entries, 100 entries, 1000000000000000000 entries?

I have used dynamically linked lists as dynamic memory before. It works like a charm but you have to allocate / deallocate carefully. C++ can solve those problems.
The key point for a constrained embedded system is that allocating dynamic memory and then later deallocating it DOES NOT return the system to the same state. You may have just introduced fragmentation in the heap that is effectively irreversible. Allocate and deallocate 10, 100, 1000... times and the system may be effectively useless.

And if you don't look at the big picture and 'gracefully' handle the error condition, you can make things worse. Oh that allocation didn't work ... shucks (instead of rebooting).

Or possibly even worse, even if you can still allocate and deallocate, it gets harder and harder for the memory manager to find free space, and the system gets slower.

C++ makes it easier to never forget to allocate/deallocate, but it also makes it easier to introduce a memory allocation where you weren't expecting it. Did you declare a variable of type Foo in a function in your hard real-time path? Oh, does Foo contain Bar, which contains SuperSmartPointerBufferArray ... and after running for 10 weeks it takes 10ms to allocate instead of 10us.
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #21 on: May 22, 2013, 03:32:41 pm »
I have used dynamically linked lists as dynamic memory before. It works like a charm but you have to allocate / deallocate carefully. C++ can solve those problems.
The key point for a constrained embedded system is that allocating dynamic memory and then later deallocating it DOES NOT return the system to the same state. You may have just introduced fragmentation in the heap that is effectively irreversible. Allocate and deallocate 10, 100, 1000... times and the system may be effectively useless.
You have to be really bad at programming if you let that happen. Even on a PC such software is not acceptable. Besides buffers consisting of dynamic linked lists can never become fragmented.
« Last Edit: May 22, 2013, 03:42:48 pm by nctnico »
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline kfitch42

  • Frequent Contributor
  • **
  • Posts: 300
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #22 on: May 22, 2013, 04:00:06 pm »
You have to be really bad at programming if you let that happen. Even on a PC such software is not acceptable.

It does happen, but on a PC with GBs of RAM and a many layers of memory management (virtual memory, the C library, per process address spaces ...) it is hard to create detrimental fragmentation.

On a memory constrained embedded system with a single flat (small) address space and a slimmed down C library you need much more care to avoid detrimental fragmentation.

I ran into a case recently where we integrated two modules that had each been used/reviewed/tested (just not together).

Module A responded to a request by allocating some memory, doing some processing, and sending back a result several seconds later, at which time it deallocated the memory.

Module B responded to a request by allocating some memory and continuously monitoring something until it got a later request to stop, at which time it deallocated the memory.

During long term testing it was found that if you sent enough requests to A and B the system eventually got unhappy (due to fragmentation). Just using A was fine. Just using B was fine.

Our solution was to declare an upper limit on the number of things B could monitor and preallocate all those buffers ... sure there are other ways to skin that cat, but we needed a quick solution since we were schedule constrained.
 

Offline kfitch42

  • Frequent Contributor
  • **
  • Posts: 300
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #23 on: May 22, 2013, 06:12:16 pm »
Besides buffers consisting of dynamic linked lists can never become fragmented.

WTF?!?

Could you explain your assertion a little better? Maybe we don't have the same definition of "dynamic linked list."

AFAICT your assertion only makes sense if you only ever have one buffer size in the system. Look at my previous post, imagine module A adds a 2K buffer to its linked list, and module B adds a 4K buffer to its list. And keep in mind there are probably also modules C through Z which occasionally allocate some little tid-bit. Run it long enough and you could have a bunch of 4K buffers with 2K of fragmentation in between each.
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #24 on: May 22, 2013, 08:18:22 pm »
Imagine you chop the memory in blocks of (say) 128 bytes. Each block of memory also has a size and a pointer which can point to a next block. If you need to store 100 bytes of memory you request 100 bytes from the allocator. The allocator looks for an empty block and returns a handle to that block. Next you call a function which puts the data into the block which updates its size to 100 bytes. If you want to store an additional 50 bytes you request the allocator to extend the buffer by 50 bytes. The allocator knows only 128 bytes fit in one block so it allocates a second block and updates the linkage pointer in the first block. The function which adds data to a buffer can now store 28 bytes in the first block and 22 bytes in the second block.

This all looks complicated but in code it can be implemented quite efficiently. Because buffers are stored as linked lists the order can be completely random. Ofcourse you need functions to put/get/append data to the buffers because you can't have pointers directly to the memory. This is a bit clunky. With C++ you could overload the [] operator and offer indexed acces to a linked-list buffer.

At some point I extended this scheme to a hybrid which also supports malloc/free. In case of malloc/realloc/free a consequtive string of empty blocks is required. However, if most of the software is using the linked blocks scheme it is possible to unfragment it and in case of a re-alloc it is allowed to return a different pointer.

I used this mostly for handling network connections which are not entirely deterministic.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 892
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #25 on: May 22, 2013, 08:51:10 pm »
[...] Ofcourse you need functions to put/get/append data to the buffers because you can't have pointers directly to the memory. This is a bit clunky. With C++ you could overload the [] operator and offer indexed acces to a linked-list buffer.
That's how the original Mac OS managed memory. Every access is a double indirection and for cases when you can't do that (e.g., DMA), you have some sort of protocol for locking a block/buffer in place. You can hide it with operator[], but it's still a lot of work to go through--you're adding a constant time factor to every access.

For memory constrained devices, static pre-allocation is still the way to go, IMO. You know what all your limits are and if some resource runs short, you probably have a better chance of handling it gracefully.

Static allocations are a lot easier to test too. You can do it with a dynamic allocator, but your usage model (and your test suite) have to account for all the different permutations of allocating and freeing blocks. By the time you account for the ways in which a dynamic system can fail, you've probably spent more effort than you would to pre-allocate everything in the first place.
 

Offline kfitch42

  • Frequent Contributor
  • **
  • Posts: 300
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #26 on: May 22, 2013, 09:04:37 pm »
That is a great scheme, you have effectively recreated an MMU/Virtual-Memory in software. It is also a great fit for low level network level stuff which is all about moving streams of bytes around.

At some point that low level network code is going to hand stuff off to the 'application' layer where this type of scheme is less of a good match. Generally you will have taken that stream of bytes and transformed it into a usable structure/object. Your network layer scheme resembles my 'module A' and the application layer 'module B'. So in a simple approach their interaction can yield fragmentation. Adding the extra indirection to the network layer, which enables defragmentation definitely would help, at the expense of less determinism (in time) in allocation (which might be OK). But, once you start allowing real pointers, then fragmentation related issues could crop up.
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #27 on: May 22, 2013, 09:16:36 pm »
At some point that low level network code is going to hand stuff off to the 'application' layer where this type of scheme is less of a good match. Generally you will have taken that stream of bytes and transformed it into a usable structure/object. Your network layer scheme resembles my 'module A' and the application layer 'module B'.
At that point the data is usually on the stack in case of UDP. By limiting the packet size you can limit the amount of stack space needed. In case of TCP procotols like HTTP you'd need to traverse through the buffers and somehow turn the information from the headers into a more useful form.
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 #28 on: May 23, 2013, 02:54:25 am »
Pooled allocators are pretty common in realtime system as well since the execution cost of dynamic allocation can be pretty prohibitive(in addition to the fragmentation benefits).
 

Offline C

  • Super Contributor
  • ***
  • Posts: 1345
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #29 on: May 23, 2013, 10:29:21 am »
How much of the code created today would fit in the the category of a work around for something limited by poor compiler or poor system.

for example, I have yet to find a processor that could not do 1024 bit integer adds or subtraction in memory. If you had the two source integers in memory and memory for the result integer you could do even larger integers, yet what languages will allow you to directly define an integer of that size and do the adds/subtracts with out having to use an add on library. Now think of how little changed the compiler generated code could be for the two source integers to be in files with the result to a file.

Now think of what you could do if you could just say create this variable or structure in a heap based file named ___ instead of the memory heap. Yes a file heap var would be slower then a memory heap var but it could hidden such that only the initial create was different in the source code. A good compiler built with this could toggle a bit or two and move all the previous compiler code structures to the heap based file so the compiler would have no max program memory size limit and end up with just a heap file space limit.

where are the IDE's that work in an interactive faction with you while you are creating source code and that if you stop for a short bit tells you that your program was compiled with these errors that are highlighted in the source code or with no errors.

C
 
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #30 on: May 23, 2013, 12:31:59 pm »
where are the IDE's that work in an interactive faction with you while you are creating source code and that if you stop for a short bit tells you that your program was compiled with these errors that are highlighted in the source code or with no errors.
Eclipse does that for many languages including C and C++. The syntax is checked as you type. No need to compile.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline mikeselectricstuff

  • Super Contributor
  • ***
  • Posts: 12041
  • Country: gb
    • Mike's Electric Stuff
Re: Which is better for embedded work: C or C++?
« Reply #31 on: May 23, 2013, 02:38:33 pm »
where are the IDE's that work in an interactive faction with you while you are creating source code and that if you stop for a short bit tells you that your program was compiled with these errors that are highlighted in the source code or with no errors.

Hopefully, nowhere.
That would be really annoying. You may be part way through rearranging stuff, get interruted and return to find a confusing mess of syntax highlighting.   
I know best when something is ready to compile, not the IDE.
Realtime syntax highlighting can occasionally be useful, but probably the most useful function like this is bracket/brace matching.


« Last Edit: May 23, 2013, 02:40:20 pm by mikeselectricstuff »
Youtube channel:Taking wierd stuff apart. Very apart.
Mike's Electric Stuff: High voltage, vintage electronics etc.
Day Job: Mostly LEDs
 

Offline C

  • Super Contributor
  • ***
  • Posts: 1345
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #32 on: May 23, 2013, 04:41:31 pm »
There are a lot of great things a great IDE could do to help.
To make mike and a lot of other people happy it should always be easy to turn on and off an option.

how many times have you looked at someone else's code looking for a side effect in a function? If the IDE had access to the internal compiler data structures this would be easy. no change in what you type would be needed.

For some types of extra help to keep things simple in the long run, some extra typing is the easy thing to allow it to happen. Back in the 80's one language I used did a lot of source error checks, Think double strict what  pascal error checking does. Not only did the bit size of a var assignment have to match, but unsigned vis signed mattered as well as the type name but all you had to do was type the following "new_type_name(old_type_var)" this told the compiler that this is OK here and still allow this error checking everywhere else.
This language really under stood what a bit is so that you could easily define in an easy to read and understand structure any thing you might find in the doc's for an F3/F4 arm processor you could easily define. Want a 4 bit var, no problem, and you could use this 4 bit var in the following. If you wanted to create a disassembler you could quickly and easily create a structure for the bits in an instruction set such that you could use a case statement in the main function of the disassembler and get compile errors if you tried to access the second register bits in an instruction that only used one register.

how about helping with the links between ISR code and Main or thread code.

A lot things could be improved and some places it has even been done in special cases but there has to be some changes made to allow it to happen more main stream.

We humans get locked up with 0 or 1 when we should be using Unknown, 0 or more.

Just my thoughts,
C


 

Offline mikeselectricstuff

  • Super Contributor
  • ***
  • Posts: 12041
  • Country: gb
    • Mike's Electric Stuff
Re: Which is better for embedded work: C or C++?
« Reply #33 on: May 23, 2013, 05:10:04 pm »
A useful feature I've only ever seen in IAR's Embedded workbench is that it automatically pulls in any included files into the project tree - this makes it very quick to check names of registers in manufacturer-supplied header files without having to dig through the install directories to find them.

I'd agree that most IDEs are fairly primitive, and have little understanding of the language - there should be a better way to find references than "find in files...".
Obviously this needs tighter integration with the compiler
Youtube channel:Taking wierd stuff apart. Very apart.
Mike's Electric Stuff: High voltage, vintage electronics etc.
Day Job: Mostly LEDs
 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 892
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #34 on: May 23, 2013, 05:20:26 pm »
I'd agree that most IDEs are fairly primitive, and have little understanding of the language - there should be a better way to find references than "find in files...".
Obviously this needs tighter integration with the compiler
Meh. Keep 'em separate.

The folks who write the best compilers are usually not the folks who write the best IDEs. Except for Richard Stallman, of course (emacs is my IDE).
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #35 on: May 23, 2013, 05:58:48 pm »
A useful feature I've only ever seen in IAR's Embedded workbench is that it automatically pulls in any included files into the project tree - this makes it very quick to check names of registers in manufacturer-supplied header files without having to dig through the install directories to find them.

I'd agree that most IDEs are fairly primitive, and have little understanding of the language - there should be a better way to find references than "find in files...".
Obviously this needs tighter integration with the compiler
Not really. Eclipse does lots of this kind of stuff without compiling (it can understand the output of the compiler as well to show where compilation went wrong). Sometimes I have to hack bits in the Linux kernel. With Eclipse its relatively easy to navigate through the dreadfull bowl of C soup they call Linux kernel. You can even make bookmarks to remember interesting places. Want to know where the source of a function is? shift-click it and you get to that place.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline ddavidebor

  • Super Contributor
  • ***
  • Posts: 1135
  • Country: it
    • Fermium LABS website
Which is better for embedded work: C or C++?
« Reply #36 on: May 23, 2013, 08:37:44 pm »
Xcode for mac suggest you a lot of things when you write the code.
Davide Bortolami,
Fermium LABS srl
 

Offline benemorius

  • Regular Contributor
  • *
  • Posts: 173
Re: Which is better for embedded work: C or C++?
« Reply #37 on: May 23, 2013, 08:52:19 pm »

where are the IDE's that work in an interactive faction with you while you are creating source code and that if you stop for a short bit tells you that your program was compiled with these errors that are highlighted in the source code or with no errors.


Kdevelop is pioneering that effort (maybe xcode as well? haven't seen eclipse lately...) and I'm pleased to say it's coming along pretty nicely. A few years ago I couldn't stand using any IDE, but thanks to modern IDEs in recent years, I really can't imagine coding without one at this point.
 

Offline ivan747

  • Super Contributor
  • ***
  • Posts: 2018
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #38 on: May 24, 2013, 09:54:01 pm »
Xcode for mac suggest you a lot of things when you write the code.

Xcode is the smartest IDE I have seen in my life. It's very easy to do just about everything, and it not only knows about syntax errors and auto completion, it warns you of most errors while editing.

I found Eclipse rather bloated after looking at Xcode. IDEs are complex pieces of software, so you really have to learn one or two and stick with those.
« Last Edit: May 24, 2013, 09:55:53 pm by ivan747 »
 

Offline ddavidebor

  • Super Contributor
  • ***
  • Posts: 1135
  • Country: it
    • Fermium LABS website
Which is better for embedded work: C or C++?
« Reply #39 on: May 25, 2013, 05:11:29 am »
Yes, apple has really done this right.

Davide Bortolami,
Fermium LABS srl
 

Offline nradulovic

  • Newbie
  • Posts: 1
  • Country: cs
    • Embedded RT Kernel
Re: Which is better for embedded work: C or C++?
« Reply #40 on: May 29, 2013, 09:18:42 am »
I find Eclipse extremely helpful for C/C++ programming. It has reasonably nice syntax colouring, macro expansion, preprocessor conditional evaluation, various auto-completion features, code templates, code formatting, static code analysis, compile error highlight...I can't name it all.  :blah: It does take time to set it up but there are various plugins available that can save and restore Eclipse settings, so once you set it up you can easily transfer settings from one installation to another.
Fan of embedded Operating Systems
 

Offline kfitch42

  • Frequent Contributor
  • **
  • Posts: 300
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #41 on: May 29, 2013, 02:51:40 pm »
Since this thread has derailed into a discussion of Editors/IDEs (always an enjoyable holy war), I thought I would put in a plug for my favorite (and apparently no one else's) for doing C: netbeans. It has most of the same syntax highlighting/macro expansion as eclipse, but its subversion integration into the editor is the best I have ever seen. But, on the other hand I am quite sad that it seems to be slowly dying. When they removed python support I was quite pissed, and all the 'new' features seem to be about useless cloudy/webby shtuff (I guess some people actually care about that) or the latest try to make java a flash competitor (seriously JavaFx just aint gonna happen). Sun was mediocre crap, Oracle is serious crap.

It shows a bar down the left of the editor that has green for added lines, blue for modified lines, and a red arrow for deleted lines. Clicking on a colored section lets you revert or just copy paste from the previous version.


Last time I checked eclipse had something similar, BUT it was diffing against the last save (or something else useless like that) instead of the last svn checkin. If someone could show me how to get netbeans svn integration in eclipse I would switch in a heartbeat.
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #42 on: May 29, 2013, 03:20:01 pm »
If you install subversion support into Eclipse (Subversive / Mylyn) then you can compare your code against any revision and undo/redo changes. Eclipse also keeps a local history so you can go back to an older version which is quite neat if you don't use a version control system.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Online HackedFridgeMagnet

  • Super Contributor
  • ***
  • Posts: 1938
  • Country: au
Re: Which is better for embedded work: C or C++?
« Reply #43 on: May 29, 2013, 11:29:44 pm »
I posted a related question for you ntnico, but I thought it needed a new thread.
https://www.eevblog.com/forum/projects/question-design-descision-when-to-use-an-embedded-os-or-not/new/#new
 

Offline cthree

  • Frequent Contributor
  • **
  • Posts: 258
  • Country: ca
Re: Which is better for embedded work: C or C++?
« Reply #44 on: June 22, 2013, 04:43:41 am »
The topic has shifted a bit since the beginning. Who won?

The original question is a loaded one. There are a light year of difference between an ATTiny85 and say an ARM running an OS. If the code would benefit from C++ then you should consider using it but otherwise you are better off sticking to C. When you start implementing OO concepts in C then you know it's time to switch.

The golden rule is to write as much code as you need to get the job done and then stop. Abstraction makes complex systems simpler and simple systems complex. Use the right tool for the job.

My $0.05 (no more pennies)
 

Offline legacy

  • Super Contributor
  • ***
  • Posts: 4348
  • Country: ch
Re: Which is better for embedded work: C or C++?
« Reply #45 on: June 23, 2013, 09:08:35 am »
C++ may be a problematic extension of C if people are not good and methodic with it, and this may be critical for embedded devices.
 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 892
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #46 on: June 24, 2013, 04:38:06 am »
If you name stuff properly in C [namespaces] add no benefit, while allowing you to complicate the scope of things.

Piffle.
 

Offline millerb

  • Regular Contributor
  • *
  • Posts: 71
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #47 on: June 24, 2013, 05:44:01 am »
Xcode for mac suggest you a lot of things when you write the code.

Xcode is the smartest IDE I have seen in my life. It's very easy to do just about everything, and it not only knows about syntax errors and auto completion, it warns you of most errors while editing.

In my experience everything is smooth sailing with Xcode as long as your projects are straight ObjC/Cocoa. The moment you start working on non trivial sized projects with C++ libs thrown in problems start cropping up. Crashes, broken code completion and even barfed up syntax highlighting.

Quote
I found Eclipse rather bloated after looking at Xcode. IDEs are complex pieces of software, so you really have to learn one or two and stick with those.

Eclipse looks bloated compared to anything. Personally I don't find IDE's very complicated. I think a lot of what folks struggle with in IDEs is a lack of understanding regarding the underlying tools it manages for the user. Once a person understands the compilation process and all the little bits and pieces that have to work together to get the business done, the IDE ceases to appear to be this completed behemoth. And once you've learned one of the big IDEs reasonably well, you shouldn't have issues using any of the others. They're all a hell of a lot more similar than they are different.
 

Offline vvanders

  • Regular Contributor
  • *
  • Posts: 124
Re: Which is better for embedded work: C or C++?
« Reply #48 on: June 25, 2013, 01:15:50 am »
C/C++: C is almost always the best best for embedded code. You can get away with C++ if you limit the features you use and fully understand the implications, but most of what you can use is just making up for a lack of organization and discipline on the programmer's side. Namespaces are a classic example. If you name stuff properly in C they add no benefit, while allowing you to complicate the scope of things. You end up with loads of pointless getter/setter functions, sorry methods, when it would be better to just use appropriate names. For example I use _SIG for signals that must only be set or cleared and _AT for variables that must be accessed atomically for interrupt safety (i.e. turn off interrupts while accessing them).

Namespaces are a necessity when you start working with multiple codebases. Collisions are much easier, you have the ability to use aliases and other advantages. Getters/Setters will be optimized away in any half decent compiler and can be invaluable when you find out that you need then to do more then straight access.

I love C for it's emphasis on data access patterns and a bunch of other things but I would not so lightly dismiss C++. Even more so in recent days where processing power is increasing and cost for engineering is on the rise.
 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 892
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #49 on: June 25, 2013, 04:53:43 am »
How can I possibly disagree with such a devastating argument? Point well made, sir.
Adding to what vvanders already said...

I spend as more time integrating other people's code together as I do writing new stuff from scratch. When code don't use consistent naming conventions as you suggested, it can be difficult to avoid those name collisions. Ideally, you can just pull in a new library from version control (e.g., git) without modification. But when you have to fork/tweak library code just so it'll link with the rest of your project, it's annoying.

To be sure, it's possible to write good C/C++ code without using namespaces, but IMO it's easier to build re-usable libraries with them.
 

Offline PuterGeek

  • Regular Contributor
  • *
  • Posts: 88
  • Country: us
    • SolutionsPLUS engineering
Re: Which is better for embedded work: C or C++?
« Reply #50 on: June 25, 2013, 07:07:10 pm »
...C is almost always the best for embedded code...

I would modify this to C is almost always used for embedded code. Very few engineers even know C++ nor the plusses or minuses of each.

C++ can bloat code if every possible feature is used. C can bloat code if poorly designed or implemented. In fact all languages from assembly to the latest super language can be used to write bloated, crappy code.

Of course any language can also be used to write excellent, compact code. The difference in excellent and crappy largely comes down to appropriate use of tools and experience.

My recommendation would be appropriate use of C++ with good coding standards such as the JSF C++ Coding Standards (http://www.jsf.mil/downloads/documents/JSF_AV_C++_Coding_Standards_Rev_C.doc).

If C code is required, using a C++ compiler (if available) is recommended because of better compile time checking. Using a coding standard with C such as MISRA C (http://www.misra.org.uk/MISRAHome/MISRAC2012/tabid/196/Default.aspx) helps avoid some of the lurking dangers and generally produces more robust code.
 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1283
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #51 on: June 25, 2013, 08:24:06 pm »
IDE: Atmel Studio is amazing value for money (free) as you get both the Visual Studio editor and Visual Assist X. It is by far the best free embedded IDE currently available IMHO.
Agree, as i too noted in some other threads.
Quote
C/C++: C is almost always the best best for embedded code.
That is not necessarily the case. What would be the rationale for so sweeping a statement?
Quote
You can get away with C++ if you limit the features you use and fully understand the implications, but most of what you can use is just making up for a lack of organization and discipline on the programmer's side.
Actually, you get away with using C++ if your environment supports all the features you wish to use. Failing that you need to limit the more advanced features, which is often the case, but not a show stopper or usually even a major inconvenience. As for implications, i have to say that in the environments i use there don't seem to be any particular implications. Care to specify what exactly those would be.
An unorganized programmer can be so / will be so regardless of the language used. I have seen horrible C code where the only possible reward is a swift kick in the culprit's butt, as well as C++ that is close to poetic in its refinement. And everything in between and vice versa. Language selection is not a question of discipline or otherwise.
Quote
Namespaces are a classic example. If you name stuff properly in C they add no benefit, while allowing you to complicate the scope of things. You end up with loads of pointless getter/setter functions, sorry methods, when it would be better to just use appropriate names. For example I use _SIG for signals that must only be set or cleared and _AT for variables that must be accessed atomically for interrupt safety (i.e. turn off interrupts while accessing them).
Getters and setters are there for a reason. Actually the trivial implementation does not add anything over C because it will be an identical inline assignment / read. But a great benefit if you need to add side effects later, which you so often do.
You can roll your own name rules but now you have introduced an ad hoc standard for naming convention. How is that superior to using the built in mechanism in a standard environment?
Quote
I don't know any commercial programmers who use C++ for microcontrollers. On ARM you can get away with it.
Because so many commercial programmers just do it for the money, with no ambition or true interest. There is no need to be good at what you do, just to pass the absolutely minimum to get the project out the door and invoices into the mailbox.
OK, i exaggerate but my point is that commercial companies lack the motivation to progress beyond what is minimum necessary to get the job done. If C worked yesterday let's hope it will keep on working tomorrow and not rock the boat.

Remember - all growth takes place out of the comfort zone. After 30+ years of being a programmer and manager of programmers myself, i decided to try C++ in embedded hobby projects. Sure, you can't get every OO feature in a lowly AVR that you can get in a Solaris or HP-UX or big Wintel server, but then you don't want to either. Nevertheless, boy what a difference C++ makes in code organization and reuse. For me no going back to the ball and chain that is C. But YMMV.
« Last Edit: June 25, 2013, 09:13:38 pm by Kremmen »
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline benemorius

  • Regular Contributor
  • *
  • Posts: 173
Re: Which is better for embedded work: C or C++?
« Reply #52 on: June 26, 2013, 03:22:05 am »
Nevertheless, boy what a difference C++ makes in code organization and reuse. For me no going back to the ball and chain that is C. But YMMV.

I feel the need to second this and encourage anyone in an applicable position to give it at least one fair chance before deciding one way or the other.

Not having tight-ass MBAs hovering over my head I may be the exception, but I would increase the budget to make room for a more capable micro (overkill accusations notwithstanding) before I went back to vanilla C. The convenience is worth every penny and I just can't see myself going back. Writing and maintaining firmware became fun again once I gave C++ a try.
 

Offline mrflibble

  • Super Contributor
  • ***
  • Posts: 1947
  • Country: nl
Re: Which is better for embedded work: C or C++?
« Reply #53 on: June 27, 2013, 03:54:43 pm »
Nevertheless, boy what a difference C++ makes in code organization and reuse. For me no going back to the ball and chain that is C. But YMMV.
I feel the need to second this and encourage anyone in an applicable position to give it at least one fair chance before deciding one way or the other.
Guess I'll third that. Lately I'm playing around with both C++ and ChibiOS to see what works and what doesn't, and so far I am liking it. C++ really makes things a lot more organized for a minimum of effort. As opposed to C where you can also make things nice and organized, but that does take more work. And not to start a seperate RTOS or plain single threaded huge main() loop / roll your own threading ... I must say so far chibios is damn nice. I also checked freertos a bit, but decided to go with chibios. Not in the least because the stm32 support looks to be pretty good.

On the subject of constructors ... how do you guys handle that for embedded? Right now I have static objects with public constructors so it's known at compile time. Constructors get called in random order at run time before main() entry ... so I only do some simple things like internal variable bookkeeping there. Any order dependant things like hardware initialization I plunk in an Init() method which then gets called in the proper order from main(). That seemed a bit more sensible than putting hardware config in the constructors and then somehow (crt0.o ?) forcing a specific order. Is that the right way to go about things or are there better alternatives?

 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 892
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #54 on: June 27, 2013, 05:06:28 pm »
On the subject of constructors ... how do you guys handle that for embedded? Right now I have static objects with public constructors so it's known at compile time. Constructors get called in random order at run time before main() entry ... so I only do some simple things like internal variable bookkeeping there. Any order dependant things like hardware initialization I plunk in an Init() method which then gets called in the proper order from main(). That seemed a bit more sensible than putting hardware config in the constructors and then somehow (crt0.o ?) forcing a specific order. Is that the right way to go about things or are there better alternatives?
I try to have only a few objects hanging out at the "top level", since that's where the init order becomes unpredictable. Sometimes I'll just have a big Application object that keeps all of its state in member variables (e.g., a display buffer, ADC data buffer, threads, etc.). Within a class, initialization order is well defined.

When all else fails, there's always __attribute__ ((init_priority(X))).

I do the same kind of thing with init() methods. If you're flipping GPIOs and setting up hardware, you probably don't want that stuff happening in a constructor before main() is called or, for example, before clocks are set up.
 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1283
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #55 on: June 27, 2013, 05:48:38 pm »
On the subject of constructors ... how do you guys handle that for embedded? Right now I have static objects with public constructors so it's known at compile time. Constructors get called in random order at run time before main() entry ... so I only do some simple things like internal variable bookkeeping there. Any order dependant things like hardware initialization I plunk in an Init() method which then gets called in the proper order from main(). That seemed a bit more sensible than putting hardware config in the constructors and then somehow (crt0.o ?) forcing a specific order. Is that the right way to go about things or are there better alternatives?
Don't know about something being more right than something else. I tend to do exactly what you are doing. init_priority is the method supported by the environment (at least gcc) and that would be the way i guess, if you dont want to / can't init() from main. Of course the alternative is to construct the objects at runtime using new(). Then that question does not raise its head but dynamic memory allocation may not always be a good idea, at least in safety critical applications. That said, i have used dynamic object trees for e.g. activity sequencing and runtime sequence editing with no problems. Actually the code for that was very clean if i may say so myself.
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline mrflibble

  • Super Contributor
  • ***
  • Posts: 1947
  • Country: nl
Re: Which is better for embedded work: C or C++?
« Reply #56 on: June 27, 2013, 06:02:01 pm »
If you're flipping GPIOs and setting up hardware, you probably don't want that stuff happening in a constructor before main() is called or, for example, before clocks are set up.
That was pretty much my thinking as well. Plus, reading the order of Init() calls in main() is probably a bit more transparent than a bunch of init_priorities. Both easier for future me as well as other hapless victims.

And for the current chibios stuff this choice is even easier, since I'd like to call my Init()'s after halInit() has been called.
 

Offline vvanders

  • Regular Contributor
  • *
  • Posts: 124
Re: Which is better for embedded work: C or C++?
« Reply #57 on: June 28, 2013, 02:08:57 am »
On the subject of constructors ... how do you guys handle that for embedded? Right now I have static objects with public constructors so it's known at compile time. Constructors get called in random order at run time before main() entry ... so I only do some simple things like internal variable bookkeeping there. Any order dependant things like hardware initialization I plunk in an Init() method which then gets called in the proper order from main(). That seemed a bit more sensible than putting hardware config in the constructors and then somehow (crt0.o ?) forcing a specific order. Is that the right way to go about things or are there better alternatives?
Pretty much, anything more than trivial value initialization shouldn't be done in constructors. Initialization should be done explicitly to control the order of things, static globals with non-trivial constructors as a recipe for disaster.
 

Offline mrflibble

  • Super Contributor
  • ***
  • Posts: 1947
  • Country: nl
Re: Which is better for embedded work: C or C++?
« Reply #58 on: June 28, 2013, 03:21:28 pm »
I guess this is why some people actually RTFM and verify on a forum to be aware of limitations, and then work accordingly. But whatever floats your boat, if you like C stick with it. As for C++ being fault inducing ... not to worry, you don't need C++ for that. I've seen all manner of crap, asm, C, C++. And I've seen all manner of good code, asm, C, C++.

Easy to follow plan:
1 - pick right tool for the job
2 - don't suck at using this tool
3 - profit
 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1283
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #59 on: June 28, 2013, 03:54:39 pm »
Constructors are basically useless. What can you do with them? Set some default values... Well, you can just do that when the variables are defined. Can't allocate anything non-static anyway. Can't set up any hardware before main() has run, and running order isn't guaranteed.
Oh please. Now you erected a straw man and kicked it down. While it is true that for a trivial object you don't need much of a constructor, that doesn't mean constructors (and destructors) are useless. Static class instances don't go in and out of scope so construction and destruction are not relevant for them in the same way as for true dynamic instances, but that is not at all a problem of the construction mechanism, so criticizing it misses the mark.
Quote

This is what I mean about C++ causing problems because people aren't fully aware of the consequences of trying to use certain features. With static constructors it isn't even possible to tell what order start-up code will execute in.

I guess this is why some people actually RTFM [...]

2 - don't suck at using this tool

[...]
This is the solution.
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline Rufus

  • Super Contributor
  • ***
  • Posts: 2094
Re: Which is better for embedded work: C or C++?
« Reply #60 on: June 28, 2013, 04:41:32 pm »
Constructors are basically useless. What can you do with them? Set some default values... Well, you can just do that when the variables are defined.

Some people just don't get OOP which makes me question their ability to get anything really.

As for constructing statics, allocating something once at start up and never freeing it isn't dynamic and should be of no concern in embedded systems. A heap manager which doesn't have to free anything can be implemented in 3-4 lines of code. There is also placement new which no one mentioned yet.
 

Offline ToBeFrank

  • Regular Contributor
  • *
  • Posts: 234
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #61 on: June 28, 2013, 08:19:34 pm »
Constructors are basically useless. What can you do with them? Set some default values... Well, you can just do that when the variables are defined.

Only if you're using C++11.
 

Offline Jeroen3

  • Super Contributor
  • ***
  • Posts: 3331
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: Which is better for embedded work: C or C++?
« Reply #62 on: June 28, 2013, 08:38:37 pm »
Our DSP teacher has said more then a few times that the C++ compiler creates better assembler then the C compiler. Not sure in what area of better, faster or smaller?
But it makes complete sense to use C++ for all the bonus features you will get above C. Like templates types, objects, overloading, default arguments.
Using object oriented in C with structures doesn't compete with C++ with coding comfort. .

And also, looking at micro controllers, every peripheral can be an object, including driver code. Instead of a structure of registers, and driver functions separate.

However, when using C++ with fancy dynamic memory you don't want to end up creating a lot of objects on stack (eg. inside a function) that's incredibly slow!
And you should definitely be aware that your few kB of sram are very limited.

In the end it does not matter a lot, if you give the compiler and optimizer enough hints it can make efficient assembler.
That is the main goal for micro controller programmers, compiling efficient code. This can be done with C or C++, choose the one that gives you most comfort.

Also, I've seen the term "x lines of code". One line of code can take up quite a lot of cpu time. For example this: "volatile double x *= 6.5444;". It's "just one line", but is can take more than 1KB of instructions on some architectures.
« Last Edit: June 28, 2013, 08:44:36 pm by Jeroen3 »
 

Offline ToBeFrank

  • Regular Contributor
  • *
  • Posts: 234
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #63 on: June 28, 2013, 08:46:47 pm »
However, when using C++ with fancy dynamic memory you don't want to end up creating a lot of objects on stack (eg. inside a function) that's incredibly slow!

I think you meant this but for clarification... allocating objects on the stack in C++ is the same speed as in C (a class is essentially a struct). If the object being allocated uses dynamic memory in its constructor, the allocation on the stack would be slow, but otherwise stack allocation is very fast.
 

Offline ToBeFrank

  • Regular Contributor
  • *
  • Posts: 234
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #64 on: June 28, 2013, 10:45:23 pm »
You can't rely on constructors because sometimes you need to set stuff up in sequence after other things, so you will end up with a mix of constructors that execute in random order and a load of init() methods you then call later.

More clarification... class member variable constructors are called in the order the member variables were declared. Static initializers have no guaranteed order.
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #65 on: June 28, 2013, 11:15:21 pm »
Oh please. Now you erected a straw man and kicked it down. While it is true that for a trivial object you don't need much of a constructor, that doesn't mean constructors (and destructors) are useless. Static class instances don't go in and out of scope so construction and destruction are not relevant for them in the same way as for true dynamic instances, but that is not at all a problem of the construction mechanism, so criticizing it misses the mark.

You are thinking too abstractly, which is exactly what I was talking about. You say the construction mechanism itself is not a problem which is in some sense true. The problem is you can't separate the abstract concept of the constructor mechanism and the practical implementation in an embedded system. It works on the desktop, but not for embedded.
You clearly have the concepts wrong. A constructor which doesn't construct anything is an empty function which is optimised away. Secondly the others already stated that they instantiate the objects statically which means there is no dynamic memory usage other than the stack which you have with C as well. All in all your objections have no ground.
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 #66 on: June 28, 2013, 11:26:10 pm »
Constructors aren't useless, they just aren't very useful.

C++ is something of an ugly implementation of OO in my personal opinion, second only to Java.
 

Offline Rufus

  • Super Contributor
  • ***
  • Posts: 2094
Re: Which is better for embedded work: C or C++?
« Reply #67 on: June 28, 2013, 11:30:27 pm »
<snip another straw man argument>

What you are actually saying is you don't know how much stack is required but while the compiler spits out a number which makes the stack space look big you are not bothered about it and if someone reduces memory available for the stack in the future it is their responsibility to check the number the compiler spits out and make some value judgement and worry about it. If they don't ("because they thought they were safe or didn't understand the implications of what they were doing") they get just the same horrid stack/variable overwriting bugs which you attribute to heap memory allocation on start up.

 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1283
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #68 on: June 29, 2013, 06:46:29 am »
Oh please. Now you erected a straw man and kicked it down. While it is true that for a trivial object you don't need much of a constructor, that doesn't mean constructors (and destructors) are useless. Static class instances don't go in and out of scope so construction and destruction are not relevant for them in the same way as for true dynamic instances, but that is not at all a problem of the construction mechanism, so criticizing it misses the mark.

You are thinking too abstractly, which is exactly what I was talking about. You say the construction mechanism itself is not a problem which is in some sense true. The problem is you can't separate the abstract concept of the constructor mechanism and the practical implementation in an embedded system. It works on the desktop, but not for embedded.

All the constructor will do is add bloat. You can't rely on constructors because sometimes you need to set stuff up in sequence after other things, so you will end up with a mix of constructors that execute in random order and a load of init() methods you then call later. You might as well just stick everything in the init() methods.
Sure, an object instance must be constructed but why is that a problem? You are free to influence the actual construction in a number of ways, such as defining all instances static if you really don't want to do anything during runtime. But if you do choose to create objects during runtime, they must be constructed at least in the minimal way of allocating the space for member variables. That part you cannot separate (and why would you want to?) but everything else can be put in a separate init() method that you are free to call if and whenever you want to. Contrary to what you imply it is not at all rare in desktop and server environments either. It is just a question of what is practical. Because if you _don't_ want to use init()s then just define init_priority and be done with it.
Much is made now of this initialization order and for MCU hardware it sometimes (but not always and in every case) matters. That particular problem is easily solved in a number of ways. Otherwise the question of construction order is either uninteresting or defined by control flow and scope visibility.
Quote
People don't like doing that though because on the desktop the paradigm is to always do certain things in the constructor because then by convention people know where to find them. It just don't work for embedded.
The paradigm of construction comes from the language definition, not from what "people like to do". Constructor is the place to initialize a class instance and there should be a reason not to do it there. Using the init() method is potentially risky if only a default constructor is used since then the member variables might be uninitialized. Accidentally calling a method before init() could cause problems. The really proper way for static, order dependent instances would be to implement a minimal constructor that puts the instance into a coherent state, and then later call the init().
I have yet to find out how construction doesn't work for the embedded software since it patently does. Yes, there is a cost to construction but the minimal cost is not really any different from allocating a struct in C. Calling that bloat is IMO unjustified. Anything else a constructor does is application code and needs doing anyway so is by default excluded from any language caused bloat. At this very reasonable cost you get all the benefits of potentially polymorphic object creation shifting the balance easily to C++ as far as i am concerned.

For some reason the discussion of constructors revolves only around initializing member variables. Sure, that always happens but it is not at all the only thing a constructor is good for. The recurring "problem" of dynamic memory allocation is supposed to lead to disaster always in the end. It is supposed to be so hard to detect when the system runs out of memory yada yada. Sure, keep allocating memory and eventually you will run out. However it is not like you can't do anything to avoid running into a brick wall at full throttle. Firstly, not all dynamic allocations just keep piling up. You might wish to construct alternative versions of an object, but only a limited number or just one at a time. Second, if you do need to allocate an unknown number of instances and you absolutely must not run out of memory (at least without realizing it), there are ways. The way i would choose is a class factory design pattern. The static factory instances allocate a fixed block of memory (yes) and use that to dish out memory for the instances they create by request. Now if you run out of memory in the block the program doesn't just crash. The factory can either just inform the caller of this sad state of affairs, or it can negotiate more memory for itself, should any be available and fulfill the request. Its all quite doable with less lines of code you might think. The nice thing is that it is configurable to do what makes sense in each particular application so code reuse is high. Effectively it does just what a vanilla C allocator does, but hiding the implementation from the calling party, thus making the caller independent of the solution - exactly the point of reuse. Plus, you are free to decide on a recovery strategy if that is wanted - something that would be at least cumbersome to arrange in C code.
But then you can always pre-allocate everything in the old fashioned way. It is equally secure but you need to hope you got your allocation ratios right. It would be sad if one pool is exhausted stopping the application while plenty of free memory remains available in other pools.
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline Jeroen3

  • Super Contributor
  • ***
  • Posts: 3331
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: Which is better for embedded work: C or C++?
« Reply #69 on: June 29, 2013, 10:57:19 am »
In embedded application, especially automotive or other certified, you don't want to be able to create an unknown number of instances of an object. You always want your memory usage to be predictable.

You can perfectly dynamically create a static task. *huh what?*
Just create a fixed number and never delete them.

And take for exmaple a sprintf buffer, you only need that for a short while, in a task. If you can guarantee the buffer is freed when the task is completed and your buffer operations cannot be rescheduled, you'll have low change of getting memory trouble. After the sprintf task you can then use that memory for an SD card task for example.

But the safest possible way is to pre-allocate everything.

To the constructors, they are just functions called when the object is allocated to initialize stuff. Even your "int main(void)" has a constructor, its called startup.s.
If you have normal C you'd have a bunch of "struct thingy_1" with "thingy_init(thingy_1)". Same story.
 

Offline Rufus

  • Super Contributor
  • ***
  • Posts: 2094
Re: Which is better for embedded work: C or C++?
« Reply #70 on: June 29, 2013, 12:31:45 pm »
No, I'm saying that you can calculate exactly how much stack space is required by any given program as long as everything is statically allocated and you don't do any unbound recursion.

Variables being allocated statically or dynamically has a tiny influence on stack requirement and zero influence on the difficulty of calculating exact stack requirements.
 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 892
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #71 on: June 29, 2013, 03:12:52 pm »
When you statically allocate everything by defining it in code and hit the compile button you get number back telling you how much RAM has been allocated. The rest is free for stack. You know exactly how much you have and how close you are to running out. If, five years down the line, someone comes along and decides they need a few hundred bytes for a buffer they will quickly notice that after defining it the available RAM is dangerously low.

On the other hand if you allocate stuff at run-time you could easily end up with insufficient free space.
This is a really good point. In my own mcu code, I try to avoid dynamic memory allocation for this very reason. Sometimes it creeps back in debug builds because of printf, but that's livable.

However, C++ doesn't require dynamic allocation any more than C does, and whichever style of allocation you prefer will work in both language. Personally, I use constructors in C++ frequently in code with statically allocated objects. For example, suppose there's a Display class that draws data from a Buffer. In C++, I'd have the Display constructor accept a const reference to the Buffer:

Code: [Select]
class Display {
  const Buffer &data;

 public:
  Display(const Buffer &b) : data(b) {}
  // other methods here
};

// static variables
Buffer gData;
Display gDisplay(gData);
If I end up changing the name of the Buffer instance, there's no need to modify the Display implementation at all, because the coupling between the classes is very weak. In contrast, most embedded C that I've run across would have the Display functions directly reference the buffer variable with much tighter coupling. To be sure, these are stylistic points, but IMO it's easier to maintain code that separates concerns well, and C++ makes that more easy than C.
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #72 on: June 29, 2013, 04:50:46 pm »
In embedded application, especially automotive or other certified, you don't want to be able to create an unknown number of instances of an object. You always want your memory usage to be predictable.

You can perfectly dynamically create a static task. *huh what?*
Just create a fixed number and never delete them.
Thats another way to do it. The whole point is that you need to create a situation in which the memory usage is 100% predictable.
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 #73 on: June 29, 2013, 05:05:37 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.

I come from the games space where performance and memory is just as critical as in the MCU space. You've got 16.6ms to update thousands of objects, and render them. You're constantly pushing against memory limits to hit the best fidelity that you can get. Every engine I've worked with that's hit this target has:
  • Used C++
  • Not done dynamic memory allocation
Using fixed pooled allocators with placement new you can get completely predictable memory usage and all of the benefits that come with C++. Hell, I've even seen scripting languages used inside of 400kb fixed space allocation. I'm talking about shipped products here and not just hobby projects.

Since C++ is just a superset of C it's not the language but how you choose to used it.
 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1283
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #74 on: June 29, 2013, 05:21:17 pm »
The paradigm of construction comes from the language definition

That is the problem. The paradigm is designed for systems where things are dynamically allocated. Shoe-horning it into an embedded system isn't a good idea.
The border between "embedded" and general purpose is a line somewhat drawn in water. For sure Stroustrup & co never made such a distinction. Nowhere in the language is there a requirement to allocate anything dynamically so using that as an argument against the language again misses the mark. Please don't make dynamic allocation a required feature of C++ which you can then shoot down and thereby dismiss the language in embedded solutions. It just isn't so.
I largely agree with those who warn against careless use of dynamic memory in resource constrained systems but that is not a problem of the language, only its usage.
I hope it is by now obvious to all that offhand dismissing something that is actually widely used with good success is not a fact but opinion only. We are all entitled to those of course.
Nothing sings like a kilovolt.
Dr W. Bishop
 

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: 1283
  • 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: 1947
  • 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: 2094
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: 17998
  • 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: 17998
  • 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: 3331
  • 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: 17998
  • 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 andyturk

  • Frequent Contributor
  • **
  • Posts: 892
  • 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: 1217
  • 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: 1217
  • 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: 1283
  • 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: 1283
  • 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: 2009
  • 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: 246
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: 17998
  • 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: 4348
  • 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: 4348
  • 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: 1947
  • 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.
 

Offline legacy

  • Super Contributor
  • ***
  • Posts: 4348
  • Country: ch
Re: Which is better for embedded work: C or C++?
« Reply #100 on: July 05, 2013, 02:04:29 pm »
You can always use the list of tools as a starting point. And when too expensive, google for equivalents that fit your requirements & budget.

Yep, misra, damn to autocorrection =P, ummm, but anything opensource to suggest ? or anything "demo" ? CosmicC for example is offering a 4K line  limited C compiler for 68hc11 and 68300, wandering if there is a sort of misra-limited to ... 4K lines of code per module.
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #101 on: July 05, 2013, 05:27:01 pm »
I like the line 'There is no MISRA certification process'... so don't bother with the tools  |O
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 #102 on: July 06, 2013, 02:26:39 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)

The second one is one of those iconic texts which you have on the shelf but never bothered to read unless someone forced you to. Everything in it is also available online just by searching for "programming patterns". Factories, Singletons, yadda, yadda. It's not a practical guide, CS theory mainly.

The only book about C that everyone needs to read is http://www.amazon.com/C-Programming-Language-2nd-Edition/dp/0131103628/ref=sr_1_1?ie=UTF8&qid=1373077313&sr=8-1&keywords=the+c+programming+language All the other books about C simply add to this cononical text. Thin, clear, concise, essential.
« Last Edit: July 06, 2013, 02:28:26 am by cthree »
 

Offline diyaudio

  • Frequent Contributor
  • **
  • Posts: 671
  • Country: za
Re: Which is better for embedded work: C or C++?
« Reply #103 on: July 06, 2013, 04:26:47 pm »
There have been a couple of interesting discussions here on software topics. Assembly vs C is one, and the ISR discussion is interesting too.

So, what about C vs C++? The question is moot for rinky-dink microcontrollers that don't have a C++ compiler, but for modern "reasonable" architectures (e.g., ARM, MSP430) it's an interesting choice. Most embedded code is straight C, but there's a growing number of C++ folks in the mcu world.

Given a choice, I'll go with C++ in a heartbeat. A major reason is that C++ makes structure initialization much more rational with constructors. C++ objects are implemented in a way that's similar to adding a compiler-managed parameter block to each function, avoiding the need to have so many static variables. Namespaces, templates, virtual functions and references only add to the C++ win.

What say you?

I'm a seasoned developer I just got into embedded development 8 months ago as a hobby as the experience is fun as im already comfortable with elementary computer science.

The point im try to make is this. C++ from a code organisation view is very good VS C however consider this, low level high performance code is written and maintained in C in fact 90% of the windows api is C as well a Linux kernel, even quake 1,2 and 3 was written in C, C++ is a very complex language to master, in fact you will end up running in circles trying to debug "C++ problems and miss understandings" then actually solving your micro-controller problem. C++ is about objects, classes advance topics like templates by the time you fully covered c++ you would be so far out at sea, you wont see micro-controller land for months !!!

 I like the elegance of nicely layered C code with logical *.h,.*c units and thick well written comments and #defines its far easy to read then C++ objects hiding the logic deep inside of classes with pointers and other complex mechanics. (only a small percentage of developers know how to logically and beautifully architect a c++ application)


If you want to explore C++ checkout Scott Meyers, he is one of the world's foremost experts on C++ and pushing C++ for embedded systems.
The Case for C++ in Embedded Systems
http://aristeia.com/TalkNotes/MISRA_Day_2010.pdf


 

« Last Edit: July 06, 2013, 04:33:47 pm by diyaudio »
 

Offline PuterGeek

  • Regular Contributor
  • *
  • Posts: 88
  • Country: us
    • SolutionsPLUS engineering
Re: Which is better for embedded work: C or C++?
« Reply #104 on: July 07, 2013, 01:24:19 am »
Thanks to the PDF diyaudio posted, I found an article on C++ performance (http://www.open-std.org/jtc1/sc22/wg21/docs/TR18015.pdf).

This dispels some of the widely held view that C++ has significant overhead and is well worth a read.

-Joe
 

Offline cthree

  • Frequent Contributor
  • **
  • Posts: 258
  • Country: ca
Re: Which is better for embedded work: C or C++?
« Reply #105 on: July 07, 2013, 05:08:54 am »
Thanks to the PDF diyaudio posted, I found an article on C++ performance (http://www.open-std.org/jtc1/sc22/wg21/docs/TR18015.pdf).

This dispels some of the widely held view that C++ has significant overhead and is well worth a read.

-Joe

There isn't much in the overhead. The tools are good. One thing though, the discussion surrounding "embedded" development seems to be one size fits all. There is a huge diversity in embedded targets. Is it a microprocessor or microcontroller? does it have a dynamic memory or static? RTOS or bare metal? Those are some huge differences.

What practical use is C++ when you're talking about 8K or 16K of compiled code running on something like an AVR with static RAM, it doesn't even have malloc() or free(). You aren't creating "instances" at run time. Once you get right down to it all you've got left is namespaces per Arduino.

It would matter on an ARM processor say with a dynamic memory controller and maybe an RTOS or at least some sort of scheduler controlling a bunch of sophisticated peripherals, etc.

Using C++ for a toaster oven or an clothes dryer might be adding unnecessary abstraction to a simple state machine.

"Embedded" covers a huge spectrum of devices and applications. There are so many applications, how can you have a single best tool to cover them all?
 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Re: Which is better for embedded work: C or C++?
« Reply #106 on: July 07, 2013, 06:04:39 am »
I have been reading and enjoying this forum for some time now. 
Normally I do not respond, but in this case I think I must. 

The debate of which higher level language to use or even what level to use is somewhat pointless. 
All non level 0 languages use reductive compilation and linking to generate native code no matter what he target. 

Any higher language could be used to generate the exact same native code. 
The things that would cause differences is the compilers used, and departures from structure. 
Every compiler is coded with reductive algorithms which include code sequence preferences. 

Every higher language with a good compiler for every target is capable of generating good code. 
The quality of code is completely dependant on:  The programers understanding of the language used, The structure of the target system, and the reductive abilities of the compiler. 
I specifically did not use the term optimization because compilers try to optimize by making many assumptions which are not always correct.  IMHO too often incorrect. 

I believe the more important discovery is finding the best compiler option for each programer. 
Ergo not everyone has the option to pay thousands for a compiler. 

Since this is my first post I guess it is customary to qualify oneself. 
In 74 I started with electronic testing and repair in 75, due to family obligations. 
In 86 I also became a Programer Analyst now know as a systems programer. 
In 89 I officially became the equivalent of a electronic technologist. 
In 92 I used both disciplines to create an AI to some aclaim.
Since then I have worked in both disciplines, but I can not and will not say on what nor where. 
But I can and will chat about my hobbies that do include electronics and programming. 

In short I know allot, and love learning much more.  This is the biggest reason I like this forum and Dave's vblog.  There are a lot of smart people here that I can learn new things from. 
 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1283
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #107 on: July 07, 2013, 07:50:27 am »

[...]
What practical use is C++ when you're talking about 8K or 16K of compiled code running on something like an AVR with static RAM, it doesn't even have malloc() or free(). You aren't creating "instances" at run time. Once you get right down to it all you've got left is namespaces per Arduino.
:palm: Why do people have to declare things with the loud voice of ignorance, when it would be so easy to find out the truth of the matter?

Code: [Select]
#include <stdlib.h> // for malloc and free
[...]
void* operator new(size_t size) { return malloc(size); }
void operator delete(void* ptr) { free(ptr); }

And you are done. That wasn't too hard, eh?

The rest of your argument evaporates so i won't comment on that at all. This code works like a charm in Arduino and if you want to tweak, you can always change the implementation of the plain malloc/free to something more to your liking. As does for example the popular FreeRTOS OS, where you have 3 different allocators depending on what you want.

Quote

Using C++ for a toaster oven or an clothes dryer might be adding unnecessary abstraction to a simple state machine.

"Embedded" covers a huge spectrum of devices and applications. There are so many applications, how can you have a single best tool to cover them all?

Since you don't pay for what you don't use, there is no reason to pick a weaker tool for a smaller target. As C++ is a genuine superset of C, there is no reason to revert to C. Just use C++ as C if you absolutely don't want to use OO features. That will keep your toolchain and work processes intact.
I have to say that this is one of the arguments that makes least sense to me. It is perfectly understandable that if you have coded tiny environments in C there is little incentive to switch to C++ since you will face issues using the more advanced features, and accordingly don't get any benefit from the switch. But once you are committed to using C++ in larger environments where you do get the benefits, there is no compulsion to switch tools in smaller ones. Anything you can do in C you can replicate in C++ with no penalty.
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #108 on: July 07, 2013, 11:12:48 am »
The point im try to make is this. C++ from a code organisation view is very good VS C however consider this, low level high performance code is written and maintained in C in fact 90% of the windows api is C as well a Linux kernel, even quake 1,2 and 3 was written in C, C++ is a very complex language to master, in fact you will end up running in circles trying to debug "C++ problems and miss understandings" then actually solving your micro-controller problem. C++ is about objects, classes advance topics like templates by the time you fully covered c++ you would be so far out at sea, you
Now you are saying you are better of using assembly because any high level language is hard to learn. The real problem is that many EEs get a bit of programming during their study so they can dabble a bit with software. However it takes years to become a real software engineer. For some this is just beyond their reach. That doesn't make a high level language unsuitable though. You just need the right person for the job.

BTW the Linux kernel actually disproves the point you are trying to make. The Linux kernel is a large number of objects and they use plain C to emulate an OO language. Its a pretty convoluted mess. And I doubt its faster. The C++ compiler knows it is dealing with an object so it can do clever optimisations. The C compiler used on OO emulated in C sees a struct with some function pointers and data.
« Last Edit: July 07, 2013, 11:37:37 am by nctnico »
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline diyaudio

  • Frequent Contributor
  • **
  • Posts: 671
  • Country: za
Re: Which is better for embedded work: C or C++?
« Reply #109 on: July 07, 2013, 05:30:01 pm »
Oh, what an informal introduction "Now you are saying you are better of using assembly because any high level language is hard to learn."
Hello how do you do ! :)

Did you know the of best developers are the ones who master the mechanics of low level computer science example ASM -> C -> C++ (not the reverse) then move on to C++ I’m sorry if you like to put the cart before the horse, I stay far away from debates like this my point was simple C++ is a complex language to understands and not that high level, in fact it’s just an extension of C it’s not that high level compared to Java, C# which sits on top of a virtual machine, you can make c high level as well with certain amount of effort, and yes everything has its place but if you act more humble you will understand the value of mastering C.

"BTW the Linux kernel actually disproves the point you are trying to make. The Linux kernel is a large number of objects and they use plain C to emulate an OO language. Its a pretty convoluted mess. And I doubt its faster. The C++ compiler knows it is dealing with an object so it can do clever optimisations. The C compiler used on OO emulated in C sees a struct with some function pointers and data."

clever optimisations?

Code in the kernel runs in a very different environment than in user space. There is no process separation, so errors are a lot harder to recover from; exceptions are pretty much out of the question. There are different memory allocators, so it can be harder to get new and delete to work properly in a kernel context. There is less of the standard library available, making it a lot harder to use a language like C++ effectively.

Sometimes i wonder why i bother participating in useless debates like this :palm:  ( maybe it’s just to educate and warn others )





« Last Edit: July 07, 2013, 05:34:44 pm by diyaudio »
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #110 on: July 07, 2013, 05:47:45 pm »
I have to work on the Linux kernel every now and then (debugging and writing new drivers) and the whole thing is filled with exceptions: if error goto error_handler (which cleans the whole thing up). That is exactly what exceptions are for... Thinking the Linux kernel is something special is a misconception. Actually its a pretty bad piece of software with very little structure and documentation.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1283
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #111 on: July 07, 2013, 06:21:28 pm »
[blah]
Sometimes i wonder why i bother participating in useless debates like this :palm:  ( maybe it’s just to educate and warn others )
Please do educate us then but preferably by making concrete points or in fact any points, because many of us have failed to notice the fatal shortcomings you imply but don't elaborate. If you want to participate, that is... But please show some actual competence in C++ before bashing it using factual arguments.
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Re: Which is better for embedded work: C or C++?
« Reply #112 on: July 07, 2013, 06:22:04 pm »
DIYaudio I was following your argument until you called Java, C# and C++ high level lanquages.  :)
Since forever high level language has referred to level 5-7, has the term changed? 

I do find it amusing that all these mid languages originally created to make programming easier are now considered harder.  (Java and C# being exceptions.  Java started with a C++ structure to create a language for a virtualized environment.  C# is M$ attempt to automate some of the cludges for programming in their environment.).   

Many languages have been developed to help programers program properly.  Yes it takes years to learn proper programing skills, but the mid languages where intended to reduce that learning burden.  So it does take years to learn the skill to write an strong kernel or engine.  Exponentially less time higher up the abstract layer and language levels you go.  For example Delphi is suppose to allow a non programer to creat a user space app in hours. 

Yes I will accept that it would be easier to inspect level 0,1 code when nessary, if the programming learning process start bottom up.  But in reality most people have learned programming with the embarrassment of the languages, BASIC.  It is still possible for these BASIC to become great programers. 

Besides may programers will just claim a task is not possible if they can not be successful utilizing the tools and skills they have.  This annoys me but I am not the opinion police. 

 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Re: Which is better for embedded work: C or C++?
« Reply #113 on: July 07, 2013, 06:44:41 pm »
The Linux kernel is/was considered a marvel because a university student was able to successfully create a capable reverse engineered Unix kernel.  This by no means acclaimed his programming prowess.  This acclaimed his practical application of his understanding of the Unix subsystem. 
Since then he continued his development and may others have now added to the effort.  Frankly it is amazing that a one person core has survived the contributions of so many without complete rewrites.  This proves to me that his programming practices where good enough to allow this migration and therefor successful. 

Because off this everyone has access to a Unix like kernel, normally only accessible to large organizations. 
 

Offline diyaudio

  • Frequent Contributor
  • **
  • Posts: 671
  • Country: za
Re: Which is better for embedded work: C or C++?
« Reply #114 on: July 07, 2013, 07:02:16 pm »
[blah]
Sometimes i wonder why i bother participating in useless debates like this :palm:  ( maybe it’s just to educate and warn others )
Please do educate us then but preferably by making concrete points or in fact any points, because many of us have failed to notice the fatal shortcomings you imply but don't elaborate. If you want to participate, that is... But please show some actual competence in C++ before bashing it using factual arguments.
  :scared: im having a general discussion why do you wanna know whats going on under my skirt?, back off!

Quote
DIYaudio I was following your argument until you called Java, C# and C++ high level lanquages.  :)
Since forever high level language has referred to level 5-7, has the term changed?

I do find it amusing that all these mid languages originally created to make programming easier are now considered harder.  (Java and C# being exceptions.  Java started with a C++ structure to create a language for a virtualized environment.  C# is M$ attempt to automate some of the cludges for programming in their environment.).   

Many languages have been developed to help programers program properly.  Yes it takes years to learn proper programing skills, but the mid languages where intended to reduce that learning burden.  So it does take years to learn the skill to write an strong kernel or engine.  Exponentially less time higher up the abstract layer and language levels you go.  For example Delphi is suppose to allow a non programer to creat a user space app in hours.

Yes I will accept that it would be easier to inspect level 0,1 code when nessary, if the programming learning process start bottom up.  But in reality most people have learned programming with the embarrassment of the languages, BASIC.  It is still possible for these BASIC to become great programers.

Besides may programers will just claim a task is not possible if they can not be successful utilizing the tools and skills they have.  This annoys me but I am not the opinion police

In computer science, a high-level programming language is a programming language with strong abstraction from the details of the computer. In comparison to low-level programming languages.

Firstly i didn't say c++ is high level.

Java, C# are. and this is why..  if you look at the .NET framework and Java both frameworks contains a hug set of abstractions (even more the Base Class Library (BCL) v4.5) used to aid common and complex tasks such as Object Serialization, File Access, Network Communication, GUI development, Threading and many others, and further extends the "high level model" into functional language using LINQ ( .NET ) and giving birth to F#... I cannot comment much on java i only worked on it for 8 months and used spring but the client was  happy and i moved on.

Now if we turn our attention to C++ out the box it doesn't come with very much in comparison with Java and C#, there are good efforts see the "boost library" to build platform independent code with a large set of desperate libraries "missing" in the standard for everyday critical usage which makes c++ easier to work with.

(i was looking at the ASIO library for networking just last week for a MAC OS, Linux and windows network service) 

Here something im working on it uses a MICRO PIC 4550 using C, .NET C# 4.5 GUI



« Last Edit: July 07, 2013, 07:13:52 pm by diyaudio »
 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1283
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #115 on: July 07, 2013, 07:12:09 pm »
You sure have a knack at evading the point.
How is this related to C vs C++?
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline diyaudio

  • Frequent Contributor
  • **
  • Posts: 671
  • Country: za
Re: Which is better for embedded work: C or C++?
« Reply #116 on: July 07, 2013, 07:20:01 pm »
You sure have a knack at evading the point.
How is this related to C vs C++?

Oh please Kremmen, don't think im standing in front of you as if you a judge and im in court.  :wtf:
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #117 on: July 07, 2013, 07:23:45 pm »
The Linux kernel is/was considered a marvel because a university student was able to successfully create a capable reverse engineered Unix kernel.  This by no means acclaimed his programming prowess.  This acclaimed his practical application of his understanding of the Unix subsystem. 
Since then he continued his development and may others have now added to the effort.  Frankly it is amazing that a one person core has survived the contributions of so many without complete rewrites.  This proves to me that his programming practices where good enough to allow this migration and therefor successful. 
Well you should spend a couple of hundred hours digging around in the Linux source (like I have) and I'm pretty sure you won't be so enthousiastic about it. And if you compare early versions to today's version you'll see the kernel has been rewritten several times. This is why it is so hard for commercial parties to support Linux based software especially when it comes to hardware. The reasons behind changing the driver model is usually a good one but also points out the severe lack of planning and system design (specification). A while ago I reported a quite severe bug in the Linux kernel's power management which could freeze a machine during a soft reboot (and according to bug reports it did for some systems / several different platforms including PCs!). The fix was pretty simple but it turned out the new mechanism the developers where working on didn't cater for the situation. Oooops!

@diyaudio: if you want to use C++ for cross platform development I can recommend Wxwidgets. OTOH networking is pretty similar on Windows and Unix based systems so writing portable code isn't difficult.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline diyaudio

  • Frequent Contributor
  • **
  • Posts: 671
  • Country: za
Re: Which is better for embedded work: C or C++?
« Reply #118 on: July 07, 2013, 07:35:05 pm »
Quote
@diyaudio: if you want to use C++ for cross platform development I can recommend Wxwidgets. OTOH networking is pretty similar on Windows and Unix based systems so writing portable code isn't difficult.

been looking Wxwidgets sometime ago must be honest didn't get a change to evaluate it and i haven't ever built platform independent c++ code for an operating system, most of the work i do involves back-end end processing services, databases, web services and the like ( its my embedded hobby/interest  that brought me closer doing some operating system GUI work )
 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1283
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #119 on: July 07, 2013, 07:48:31 pm »
You sure have a knack at evading the point.
How is this related to C vs C++?

Oh please Kremmen, don't think im standing in front of you as if you a judge and im in court.  :wtf:
No, not at all. But also please don't talk down to the rest us as if we didn't know or understand anything. It just offends without bringing value to the conversation.
If you have a point in the debate C vs C++ then please make it.
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline mrflibble

  • Super Contributor
  • ***
  • Posts: 1947
  • Country: nl
Re: Which is better for embedded work: C or C++?
« Reply #120 on: July 07, 2013, 07:50:36 pm »
most of the work i do involves back-end end processing services, databases, web services and the like ( its my embedded hobby/interest  that brought me closer doing some operating system GUI work )

Heh, same here. Mostly it's backend stuff. The occasional simple GUI I make using Qt. Precisely because it works on linux, windoze and with a little extra prodding even on android.
 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Re: Which is better for embedded work: C or C++?
« Reply #121 on: July 07, 2013, 07:53:03 pm »
Java is level 4 not 5, 6, or7.
C# level is still in debate as far as I know. 

I believe I use the phrase complete rewrite, which it has not.  If it has been it would not be able to use the name Linux. 

I also commented on the kernels ability to survive the migration path to what it is today.  Giving credit to his knowledge of Unix and structure.  I gave credit to the man that was the first to achieve what was considered impossible at the time.  If you find this offensive to bad. 

As far as the code itself over the last decade. Yes I do find fault, as I do with most code not from a select few.  That is why I gave credit as I did.  Credit for a kernel surviving the input of so many coders and still archiving what it has. 

Yes since 1986 I have spent a lot of time in the Linux kernel, and several other kernels.  In a lot of them it is akin to juggling cats.  But I prefer to give credit where it is due.  In reality few are capable of producing a successful open architecture kernel.  Besides there is nothing stopping you from helping fix the problems. 

I relatively recently discovered the joys of closed architecture programming and have decided to get out of the open system programming rat race.  I do understand your aggravation, I just don't agree with you level of bashing others. 
 

Offline diyaudio

  • Frequent Contributor
  • **
  • Posts: 671
  • Country: za
Re: Which is better for embedded work: C or C++?
« Reply #122 on: July 07, 2013, 07:57:30 pm »
You sure have a knack at evading the point.
How is this related to C vs C++?

Oh please Kremmen, don't think im standing in front of you as if you a judge and im in court.  :wtf:
No, not at all. But also please don't talk down to the rest us as if we didn't know or understand anything. It just offends without bringing value to the conversation.
If you have a point in the debate C vs C++ then please make it.

hi Kremmen

i apologize if i came across as speaking down on you or anyone here. point taken. i don't know everything,
but i do program professionally and it puts bread on my families table, and there are things that i do take seriously and that is programming. :)


 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1283
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #123 on: July 07, 2013, 08:01:47 pm »
NASA banned malloc() for most embedded systems. It's just too much of a minefield.
Maybe for a good reason. Malloc is quite helpless if you ever actually run out of memory. Also you might want to have more sophisticated allocation strategy than that offered by vanilla malloc().
I'm sure NASA can afford to take the time to implement more deterministic solutions for memory usage, like safety-of-life applications elsewhere should do. For less critical apps malloc() or a variation can be good enough in practice. It all depends.
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Re: Which is better for embedded work: C or C++?
« Reply #124 on: July 07, 2013, 08:05:58 pm »
I just found a University that is posting a different language level naming convention.  It seems at least one University is not teaching the 0-7 language levels.  In particular this institution is grouping all levels above level 3 as High level languages.  So much for the old system. 

Wonder how they refer to the old level 5.  Apparently level 4 is now called high level OO now. 

Learned something new, don't like it, but it is new.  :)
 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1283
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #125 on: July 07, 2013, 08:31:09 pm »

hi Kremmen

i apologize if i came across as speaking down on you or anyone here. point taken. i don't know everything,
but i do program professionally and it puts bread on my families table, and there are things that i do take seriously and that is programming. :)
Accepted. Just wanted you to remember that there are others who do it as their day job as well. Myself, i have started professional programming -78 with minicomputers and embedded systems using various assemblers, PL/M, Fortran and what have you. When Nokia Data began OO software development in the last half of the 80's we started with Ada and C++. Ada was later dropped but C++ remained until i left the company in 2000. After that it has been Java and C#, although these days i manage SW development, not doing actual programing for my paycheck any more. But C++ is still fun as a hobby. My opinion there must be clear: that it is no worse than C and far better in many respects. But i am willing to discuss the issue.

Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline diyaudio

  • Frequent Contributor
  • **
  • Posts: 671
  • Country: za
Re: Which is better for embedded work: C or C++?
« Reply #126 on: July 07, 2013, 08:58:11 pm »

hi Kremmen

i apologize if i came across as speaking down on you or anyone here. point taken. i don't know everything,
but i do program professionally and it puts bread on my families table, and there are things that i do take seriously and that is programming. :)

Accepted. Just wanted you to remember that there are others who do it as their day job as well. Myself, i have started professional programming -78 with minicomputers and embedded systems using various assemblers, PL/M, Fortran and what have you. When Nokia Data began OO software development in the last half of the 80's we started with Ada and C++. Ada was later dropped but C++ remained until i left the company in 2000. After that it has been Java and C#, although these days i manage SW development, not doing actual programing for my paycheck any more. But C++ is still fun as a hobby. My opinion there must be clear: that it is no worse than C and far better in many respects. But i am willing to discuss the issue.
:-+

 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Re: Which is better for embedded work: C or C++?
« Reply #127 on: July 07, 2013, 10:22:01 pm »
Just to scare a few of us. 

Punch cards! 

Vacuums down!

I do amuse myself.  :) 
 

Offline C

  • Super Contributor
  • ***
  • Posts: 1345
  • Country: us
Re: Which is better for embedded work: C or C++?
« Reply #128 on: July 07, 2013, 11:38:49 pm »
WarSim,
That's the fancy stuff, try
paper tape
live hot patch code
and finger bone boot code (why waste money for a boot rom when it's expected to run 24:365)

C

 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Re: Which is better for embedded work: C or C++?
« Reply #129 on: July 08, 2013, 01:44:44 am »
Before my time thank goodness. 

For things like that I would have to refer to my fathers experience with the huge mechanical computers and the building sized vacume tube computers. 

Heard about them but I was too young to see any of them when they still worked. 

 

Offline cthree

  • Frequent Contributor
  • **
  • Posts: 258
  • Country: ca
Re: Which is better for embedded work: C or C++?
« Reply #130 on: July 08, 2013, 03:42:19 am »
I have been reading and enjoying this forum for some time now.
...
Normally I do not respond
...
I can not and will not say on what nor where
...
In short I know allot, and love learning much more.

NSA? Did I blow your cover? Am I in trouble?

[note to self: Book flight to Boliva ASAP]
 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Which is better for embedded work: C or C++?
« Reply #131 on: July 08, 2013, 03:54:46 am »
No I'm not in trouble yet.  :)

But you can stop guessing.  :)
 

Offline PuterGeek

  • Regular Contributor
  • *
  • Posts: 88
  • Country: us
    • SolutionsPLUS engineering
Re: Which is better for embedded work: C or C++?
« Reply #132 on: July 08, 2013, 05:20:07 am »
Just to bring us back on topic, which I assume to be bare metal (or RTOS at most), other than what has already been posted, what objective information exists to help choose between C and C++?

If you are using an 8051 or small PIC you have no choice; if you don't want to write assembly code you are using C (although there is/was a C++ compiler for PIC as well as some Basic and Forth stuff). I'm not sure about any other 8-bit MCUs so chime in with your knowledge.

A C++ compiler is available for most 16-bit processors; chime in if you know of one lacking a compiler. I believe all 32-bit processors have C++ compilers; again, chime in if I'm wrong.

Changing the question slightly, is anyone aware of any reason to NOT use a C++ compiler for a C code?
I know the C++ compiler treats C code differently in same areas but I am not aware of any of these to be show stoppers.

-Joe
 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Which is better for embedded work: C or C++?
« Reply #133 on: July 08, 2013, 06:08:59 am »
So far for 8,16,32 I have found only C compilers I am willing to use. 
Found several poor Basic, Pascal, C++, C compilers. 
Resolved to just use MPLabX and PICs until there is another option to consider. 
The XC compilers are not brilliant but are usable. 

If you do discover a C++ compiler that you would consider good.
Please let me know, I would like to try one out. 

Sorry, you are my canary on this one. 
 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1283
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #134 on: July 08, 2013, 07:11:48 am »
Just to scare a few of us. 

Punch cards! 

Vacuums down!

I do amuse myself.  :) 

WarSim,
That's the fancy stuff, try
paper tape
live hot patch code
and finger bone boot code (why waste money for a boot rom when it's expected to run 24:365)

C



Been there, done that.

Can't recall the 4 digit product code of the IBM card punch unit any more, but we had one on those in the CS lab when i was studying. Fortunately i didn't have to use it much, but some anyway.

Was a time i remembered the Alpha 1200 boot loader code and could toggle it in from the front panel without checking paper. That was able to read in the OS loader from paper tape and that in turn loaded the OS from the huge 5MB Hawk hard disk. A marvel of miniaturization that, weighing just 40 kilos. The machine only got core memory, boot ROMs weren't invented yet.

Also there was a time i knew the opcodes of the 8085 processor by heart. That was invaluable when you had to do a hot patch out in the field with an UV lamp and keypad EEPROM programmer as your only development tools, and paper printouts as the only documentation.

So, not scared but not missing those days that much either.

Scarier words:

Drum memory!

Vacuum tubes!
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline Kremmen

  • Super Contributor
  • ***
  • Posts: 1283
  • Country: fi
Re: Which is better for embedded work: C or C++?
« Reply #135 on: July 08, 2013, 07:14:44 am »
So far for 8,16,32 I have found only C compilers I am willing to use. 
Found several poor Basic, Pascal, C++, C compilers. 
Resolved to just use MPLabX and PICs until there is another option to consider. 
The XC compilers are not brilliant but are usable. 

If you do discover a C++ compiler that you would consider good.
Please let me know, I would like to try one out. 

Sorry, you are my canary on this one.

GCC. Or does it have to be available for a specific processor?
Nothing sings like a kilovolt.
Dr W. Bishop
 

Offline legacy

  • Super Contributor
  • ***
  • Posts: 4348
  • Country: ch
Re: Which is better for embedded work: C or C++?
« Reply #136 on: July 08, 2013, 01:48:56 pm »
Found several poor Basic, Pascal, C++, C compilers. 

me, too, i'd like to have a pretty pascal compiler for 68K
 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Which is better for embedded work: C or C++?
« Reply #137 on: July 08, 2013, 03:17:10 pm »
True GCC can be targeted to micro-controllers, Atmel for one. 
Actually I think I just forgot about that option. 

A while back when I was new to this micro controller thing I researched many options. 
And for a matrix of disqualifying reasons ended up only using microchips.   
I will skip the reasons, for brevity. 
Unfortunately some of the reasons of not using Atmel are still valid. 

So I would have to change my statement to a C++ compiler for MPLabX for now. 

 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Which is better for embedded work: C or C++?
« Reply #138 on: July 08, 2013, 03:28:38 pm »
Haven't had a project requiring a full microprocessor for a long time, even then I was able to mash it into a newly released micro controller. 
But as far as Pascal for processors there has been a few acceptable compilers.  Even CodeWarrior had a Pascal Compiler that had a bunch of noncompliant add-ons for their embedded processor options.  Although their embedded processor options should have been embedded OS Options.  No idea about today now. 
Delphi was PASCAL and it is still alive last I checked.  Wouldn't it be interesting if it could me targeted to a microprocessor.  Shudder.
 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Which is better for embedded work: C or C++?
« Reply #139 on: July 08, 2013, 03:35:34 pm »
<10 years ago I was still maintaining a computer that used core memory. 
Thankfully I personally never had to restring any, others I worked with had the pleasure though. 
I sure hope by now they have moved to some thing else only 20 years old by now. 
I'm not there anymore, so I don't know. 
 

Offline cthree

  • Frequent Contributor
  • **
  • Posts: 258
  • Country: ca
Re: Which is better for embedded work: C or C++?
« Reply #140 on: July 08, 2013, 03:42:34 pm »
Just to bring us back on topic, which I assume to be bare metal (or RTOS at most), other than what has already been posted, what objective information exists to help choose between C and C++?

There is none. It comes down to the quality of the tool chain at compiling code efficiently for size and how much your application would benefit from the additional abstraction offered by OO over straight C. The answer is, it depends. To say absolutely that one is always better is to commit to using the wrong tool at least some of the time for the sake of consistency all of the time. Use both and don't make that compromise.

That's how pretty much all successful embedded software works. C for the procedural and simple state machine and driver logic, assembly for fine tuning hardware performance, C++ or other OO (ObjectiveC, Java) for the application logic, and probably using the same tool chain at least for C rooted languages. Writing an ISR in C++ is batty. It's possible, just as it is possible to write an http server is assembly, but if you do then the guy who takes over your code someday is going to wonder wtf you were thinking and probably have to rewrite it so it makes so sense.

C++ to me makes sense when you are building an abstract framework which sits atop bare metal and is largely insulated from it, ie when the hardware is abstracted. For me, unless I'm going to abstract the hardware I prefer to code to bare metal in C. Some people like assembler for some things, I think the use for it is extremely narrow, like using binary instead of hexadecimal. Again, just me, everyone will have their own views and I would not imply they are wrong in any way, just different. I don't think the language has anything to do with writing clear, maintainable and reliable code. That comes down to the skill and discipline of the person writing it.
 

Offline cthree

  • Frequent Contributor
  • **
  • Posts: 258
  • Country: ca
Re: Which is better for embedded work: C or C++?
« Reply #141 on: July 08, 2013, 03:52:41 pm »
So far for 8,16,32 I have found only C compilers I am willing to use. 
Found several poor Basic, Pascal, C++, C compilers. 
Resolved to just use MPLabX and PICs until there is another option to consider. 
The XC compilers are not brilliant but are usable. 

If you do discover a C++ compiler that you would consider good.
Please let me know, I would like to try one out. 

Sorry, you are my canary on this one.

The defacto is IAR but their business model absolutely sucks ass, truly appalling. On the AVR platform their compiled code size is about 40% less than GCC's. if you need to cram big code into a little part it may be the only way though I'd rather use a bigger part, kinda depends on the situation. PiC has their own tools too but I've not used PIC so have nothing of merit to say about their tool chain.

As an indie, IAR quoted me $3600 if the 8 bit AVR toolkit and wanted the same again for every other chip, even the 32 bit AVR. Leaves a bad taste in my mouth. That's like 2 and a half mortgage payments for someone like me. They showed no interest in budging off that price either. They would rather have me walk away and not come back, for something which costs them absolutely zero dollars. Assholes.
 

Offline diyaudio

  • Frequent Contributor
  • **
  • Posts: 671
  • Country: za
Re: Which is better for embedded work: C or C++?
« Reply #142 on: July 08, 2013, 05:04:10 pm »
Quote
C++ to me makes sense when you are building an abstract framework which sits atop bare metal and is largely insulated from it, ie when the hardware is abstracted. For me, unless I'm going to abstract the hardware I prefer to code to bare metal in C. Some people like assembler for some things, I think the use for it is extremely narrow, like using binary instead of hexadecimal. Again, just me, everyone will have their own views and I would not imply they are wrong in any way, just different. I don't think the language has anything to do with writing clear, maintainable and reliable code. That comes down to the skill and discipline of the person writing it.

I think you hit the nail on this one, I support your view

I work at a higher level than C and doing C# most of the time im actually writing a lot of abstractions using patterns and  trying to apply them in large solutions where repeatable processes takes place and the need for abstartion is obvious (only when it applies and it’s tough to apply a pattern correctly to a problem i use it wisely as much as i can), however with that said vie been moving clients a lot and the worse thing is the miss use of a language the more options a developer has more abusive the solution becomes and the more muddy the intent is.
 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Which is better for embedded work: C or C++?
« Reply #143 on: July 08, 2013, 09:05:41 pm »
I believe we have been saying the same thing different ways, for the sake of the nay sayers. 
Makes me wonder did we come to consensus by attrition.  :)
 

Offline cthree

  • Frequent Contributor
  • **
  • Posts: 258
  • Country: ca
Re: Which is better for embedded work: C or C++?
« Reply #144 on: July 08, 2013, 11:01:19 pm »
Haha, don't worry, it won't last.  :-DD
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #145 on: July 09, 2013, 11:11:19 am »
I'm also sceptic. Usually there is a difference of a few percent between good compilers. But each compiler has its own settings to produce compact code and people doing comparisons often know only one compiler well. Another interesting fact is that the license for every commercial compiler prohibits the user from publishing benchmark tests against other compilers.
« Last Edit: July 09, 2013, 11:15:09 am by nctnico »
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline AlfBaz

  • Super Contributor
  • ***
  • Posts: 2009
  • Country: au
Re: Which is better for embedded work: C or C++?
« Reply #146 on: July 09, 2013, 02:02:04 pm »
40%... That is a lot and if true what are the trade offs? Speed, code construct constraints (eg don't ever call a function)
 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Which is better for embedded work: C or C++?
« Reply #147 on: July 09, 2013, 06:17:16 pm »
40%... That is a lot and if true what are the trade offs? Speed, code construct constraints (eg don't ever call a function)

Unfortunately a unilateral trade off statement is not possible.  As I said before a compiler is a reductive algorithm.  And such algorithms are greatly effected by many things like the programming "style".  Hence why several other programers are talking about knowing the compiler well. 
A compiler needs to balance many factors and this balance varies between compilers.  Yes there are switches to turn some branches on and off but the core algorithm that allows those branches is still there.  For example the banner specs, small code, efficient code ,fast code, load respecting, algorithm respecting, etc.  No compiler can do all thing in every situation.

That is why you have a few general options:
1: Know and use a selection of compilers and use the best compiler you know for task at hand. 
2: Know a few compilers and many reductive algorithms and use the closest compiler and take over where you know the compiler will not make the required choices. 
3: Forget about using compilers a just use low level code. 

Newer programers usually start with one compiler and seek out a "better" compiler when the first fails them.  They naturally go down the option 1 path.  Many programers manage to stay with option one for a very long time.  But at some time a programer will be pushed into option 2.  Hopefully by this time the programer know allot about how their various compilers work to make the transition smoother.  And some opt for option 3 and they become "specialist".  These skill are needed in the profession, just not required for everyone. 

In short there is no "best" compiler, just like there is no best language.

just use the one that irritates you the least, and learn all you can about it.  So if you do decide to change to a new compiler/language for the task, you can make a more educated decision if and where to move to.  Programming is not plug and play. 
 

Online HackedFridgeMagnet

  • Super Contributor
  • ***
  • Posts: 1938
  • Country: au
Re: Which is better for embedded work: C or C++?
« Reply #148 on: July 10, 2013, 07:47:32 am »
I too have heard a figure like 40% too, IIRC that figure was for C++ and a lot of that was to do with strings and/or other related libraries.
It would be interesting to know what the case is, and how it could be reduced.
 

Offline gnif

  • Administrator
  • *****
  • Posts: 1116
  • Country: au
Re: Which is better for embedded work: C or C++?
« Reply #149 on: July 10, 2013, 08:12:51 am »
The defacto is IAR but their business model absolutely sucks ass, truly appalling. On the AVR platform their compiled code size is about 40% less than GCC's. if you need to cram big code into a little part it may be the only way though I'd rather use a bigger part, kinda depends on the situation. PiC has their own tools too but I've not used PIC so have nothing of merit to say about their tool chain.

As an indie, IAR quoted me $3600 if the 8 bit AVR toolkit and wanted the same again for every other chip, even the 32 bit AVR. Leaves a bad taste in my mouth. That's like 2 and a half mortgage payments for someone like me. They showed no interest in budging off that price either. They would rather have me walk away and not come back, for something which costs them absolutely zero dollars. Assholes.

40%, is it really that much compared to GCC with -Os? Even so it doesn't seem worth the money. Upgrading to the next flash memory size up micro costs very little and you usually get more RAM/EEPROM too.

This is usually because of a poor linker script that is leaving behind all the additional sections normally found in an ELF, if you have a proper linker script then this size comes right down. If you use ulibc instead of libc it drops also. There are quite a few things you can do to create a tiny GCC binary.

There also are compile/linker options that ensure that dead code is pruned from the final binary that are not enabled by default in most dev environments, -Os can only do so much, you have to learn the compiler/linker if you really want to get the size down.
HostFission - Full Server Monitoring and Management Solutions.
https://hostfission.com/
https://twitter.com/HostFission

I volunteer my time to manage this server, if you would like to support this work I have a patreon here:
https://www.patreon.com/gnif
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #150 on: July 10, 2013, 10:57:37 am »
Thats only true for 8 compilers for 8 bit microcontrollers. Keil used to have web page showing a comparison between their ARM compiler and GCC showing Keil's compiler was way better. Keil had to remove that page because someone did the test again (this time with GCC's optimisation on) and Keil's compiler was nowhere near the results from GCC.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline Rufus

  • Super Contributor
  • ***
  • Posts: 2094
Re: Which is better for embedded work: C or C++?
« Reply #151 on: July 10, 2013, 12:12:19 pm »
Just spotted a good quote:

"Rule 1. Never make anything more complex than it needs to be.  OOP is sometimes a hammer looking for a nail when the problem is a screw."?

You continue not to 'get' it.
 

Offline mrflibble

  • Super Contributor
  • ***
  • Posts: 1947
  • Country: nl
Re: Which is better for embedded work: C or C++?
« Reply #152 on: July 10, 2013, 12:32:23 pm »
Just spotted a good quote:

"Rule 1. Never make anything more complex than it needs to be.  OOP is sometimes a hammer looking for a nail when the problem is a screw."?

You continue not to 'get' it.

Well, at least he partially got it.

Rule 1. Never make anything more complex than it needs to be.

Fixed. The rest was excess fluff that did not add any value.
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #153 on: July 10, 2013, 03:31:52 pm »
The problem is that it takes real skills and a lot of thinking to actually make something simple.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline Rufus

  • Super Contributor
  • ***
  • Posts: 2094
Re: Which is better for embedded work: C or C++?
« Reply #154 on: July 10, 2013, 04:58:30 pm »
The problem is that it takes real skills and a lot of thinking to actually make something simple.

Complex problems require complex solutions. The answer is to use methodology and tools which help you manage the complexity.

That is why trying to criticise OOP for being too complex is so not getting it.
 

Offline WarSim

  • Frequent Contributor
  • **
  • Posts: 514
Which is better for embedded work: C or C++?
« Reply #155 on: July 11, 2013, 12:59:01 am »
I would like to remind everyone that C and C++ are not separate languages. 
C++ is the abstraction layer of C. 
Originally C++ was only a pre-processor for C compilers. 

C++ generate C compliant code structures for the linker. 
The only thing that changed is the pre-processor and compilation are done with the same tool instead of two steps with two tools. 
It is possible to use a C++ compiler to generate C code if it supports inter-process dumps. 

The discussion is not about which language is better,
The discussion is if the use of abstraction / OO layer is required all the time. 

My answer is no I don't think every programming project requires C++ abstraction every time. 
Of course the C++ abstraction layer is great tool in some cases, for the same reasons it was created in the first place. 
 

Offline cthree

  • Frequent Contributor
  • **
  • Posts: 258
  • Country: ca
Re: Which is better for embedded work: C or C++?
« Reply #156 on: July 11, 2013, 01:14:56 am »
The 40% code size reduction for AVR comes from Atmel in regards to their BitCloud ZigBee stack. They published it in one of their app notes showing the FLASH requirements of BitCloud when compiled with GCC vs IAR. The difference is right about 40%.

ataradov wrote BitCloud, maybe he could elaborate on the differences but I will say that when built for the atmega128rfa1 GCC leaves about 6k flash left for the application vs over 50k when built with IAR. I can't remember the exact numbers but it was ~120k of code vs ~60k. I think it is in an app note but I'll have to dig around to find it.

GCC isn't a great compiler but it is free and open source. Those two things don't necessarily go hand in hand.
« Last Edit: July 11, 2013, 01:18:32 am by cthree »
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #157 on: July 11, 2013, 01:52:22 am »
I think I found the appnote but its 16k versus 12k. The difference is usually in the libraries. Where GCC usually comes with standard (full blown) libraries commercial compiler vendors usually provide lightweight libraries. For my projects I use the extremely lightweight C library which comes with mspgcc but it takes a little bit of effort to compile for ARM or other platforms. The bottom line is: with large differences someone probably did something wrong. The amount of development effort being put into GCC dwarfs the amount of effort a commercial compiler vendor can put into their product.
« Last Edit: July 11, 2013, 01:55:54 am by nctnico »
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 #158 on: July 11, 2013, 02:42:24 pm »
I think I found the appnote but its 16k versus 12k. The difference is usually in the libraries. Where GCC usually comes with standard (full blown) libraries commercial compiler vendors usually provide lightweight libraries. For my projects I use the extremely lightweight C library which comes with mspgcc but it takes a little bit of effort to compile for ARM or other platforms. The bottom line is: with large differences someone probably did something wrong. The amount of development effort being put into GCC dwarfs the amount of effort a commercial compiler vendor can put into their product.

That isn't exactly true. The amount of work going into GCC is mainly targeted at microprocessor systems, not embedded systems. On the embedded side there is very little work going into it. Hence the large gap in code density. The work going in is multiprocessing, virtualization, security, gpu not cramming as much code as possible into 8k of flash. IAR gets a leg up in this area because while the total effort going in may be less it is going toward things which matter to embedded developers. That is my logic reasoning anyway, not that I have any facts to back it up.

As you say, the standard libraries are not optimized for embedded microcontrollers and it was never designed to build for 8-bit systems or systems without a memory manager.

Another thing which ties the hands of GCC developers is IP and patent licensing. GCC has to work around patented processes, it can't license them like a commercial tool vendor can. Some optimizations may simplest not be available.

I'm not saying GCC is bad or wanky, just not the best tool chain, especially on embedded systems. Even Apple has phased out GCC in favor of LLVM and clang which leaves arm Linux and AVR/arduino as the only significant embedded platforms. Correct me if I'm wrong but GCC is far from optimal on embedded systems, especially 8bit microcontrollers
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 17998
  • Country: nl
    • NCT Developments
Re: Which is better for embedded work: C or C++?
« Reply #159 on: July 11, 2013, 10:25:06 pm »
I'm not saying GCC is bad or wanky, just not the best tool chain, especially on embedded systems. Even Apple has phased out GCC in favor of LLVM and clang which leaves arm Linux and AVR/arduino as the only significant embedded platforms. Correct me if I'm wrong but GCC is far from optimal on embedded systems, especially 8bit microcontrollers
Like I typed before: writing a compiler for convoluted 8 bit platforms like 8051 and PIC is an art in itself. Keil's 8051 compiler really does miracles but for mainstream 16 and 32 bit microcontrollers (68k, H8, MSP430, MIPS, ARM) GCC performs excellent. IMHO what Mojo-chan says about GCC goes for any compiler: you need to know what kind of optimisation is best for your project and use those compiler options. That takes some reading and experimenting. Usually you can get away with -O3 and -Os (with ARM code there is a difference in speed).
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline PuterGeek

  • Regular Contributor
  • *
  • Posts: 88
  • Country: us
    • SolutionsPLUS engineering
Re: Which is better for embedded work: C or C++?
« Reply #160 on: July 12, 2013, 02:08:13 am »
... GCC is mainly targeted at microprocessor systems, not embedded systems.

While the primary target for GCC is Linux systems, those systems are targeting embedded applications more and more. If the target processor is ARM, the performance is pretty good and AVR processors have good support. No other commonly used bare metal processors are supported.

Atmel provides a version of GCC in Atmel Studio and ARM supports the free GNU Tools for ARM Embedded Processors (https://launchpad.net/gcc-arm-embedded). Both include libraries targeted for embedded use.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf