Author Topic: C++ for the Embedded Programmer  (Read 26841 times)

0 Members and 1 Guest are viewing this topic.

Offline Fungus

  • Super Contributor
  • ***
  • Posts: 16561
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #50 on: March 20, 2018, 03:42:23 am »
IMHO C++ is more than being able to use OO

Yep.

... and you can code OO style in regular C as well.

True, but it's more typing and more bug-prone.

The big advantage of C++ is that you can avoid using pointers to a large extend and thus make code more reliable.

That, and a few dozen other things.

You're right on the money though, C++ is all about increased reliability and less bugs. Every time you can make the compiler do a bit more work for you then your code improves.

A good example of this is the "+=" operator.

eg. Which is best:

Code: [Select]
myVariableX += 1;

or

Code: [Select]
myVariableX = myVariableX + 1;

Obviously the first one. I doubt anybody will disagree that it's easier to get right, makes it easier to see errors, makes code more reliable.

Every time I hear a C programmer say "C can do everything the C++ can!" I want to ask them if they'd take the "+=" out of C.

It's not needed, right?


« Last Edit: March 20, 2018, 04:32:06 am by Fungus »
 

Offline Brumby

  • Supporter
  • ****
  • Posts: 12288
  • Country: au
Re: C++ for the Embedded Programmer
« Reply #51 on: March 20, 2018, 04:09:21 am »
Every time I hear a C programmer say "C can do everything the C++ can!" I want to ask them if they'd take the "+=" out of C.

It's not needed, right?

That's a difference in syntax - and whatever benefits do or do not accrue - there is nothing functionally better in the executable.

Anyway, I'm not into the "this" is better than "that" head butting.  A lot of the time it is what people know that they champion.  There's no way to have a winner there.
 

Offline Fungus

  • Super Contributor
  • ***
  • Posts: 16561
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #52 on: March 20, 2018, 04:11:31 am »
Careful use of the C scoping rules neatly solves any namespace issues.

Only if you're working in isolation and always get to pick names which don't exist yet.

Even then you'll have problems writing large programs, eventually all your function names will become longer and longer to avoid clashes with existing functions.

C++ has many other advantages when it comes to naming functions, eg. you can have several functions with the same name!

In Arduino you can type:

Code: [Select]
Serial.print(123);
Serial.print(123, HEX);
Serial.print(1.23);
Serial.print("Hello, world!");

In C it would be something like:

Code: [Select]
printSerialInt(Serial, 123);
printSerialIntHex(Serial, 123);
printSerialFloat(Serial, 1.23);
printSerialString(Serial, "Hello, world!");

Yes, the second one does work correctly, but...  :horse:


Pointers are not a problem if you are careful.  I've certainly fixed a *lot* of null pointer problems. but I can't recall any I made.  But my standard style includes a lot of:

if( !ptr ){
   // report null pointer and exit
}else{
   // get the job done
}

You can do that in C++ as well. Are you rejecting C++ because of things like this?  :scared:


I once had an assignment to write a string substitution routine.  Given a string "old" substitute string "new". This was given to me because I had all my scientific routines done and they were trying to keep me busy.   I wrote it twice, once in C and once in C++.  The C++ version was 3 times as long as the C version to do the same thing.  I don't recall which the project used.  I'd guess the C++ version, but that's just a guess.

Code, or it didn't happen.

(and probably had a memory leak)

At about this time ('97-98) Les Hatton published a paper in the ACM journal discussing the statistics of several years maintenance on the static code analyzers his company sold.  The C analyzer was written in C and the C++ analyzer was written in C++.  The programming staff were analyzing C and C++ code for errors, so they were quite expert in both languages out of necessity.  The mean time to fix a bug on the C++ analyzer was significantly longer than the C analyzer.  Les later wrote a book, "Safer C".

What if he'd written the C analyzer in C++ and the C++ analyzer in C?  :-//  :popcorn:

« Last Edit: March 20, 2018, 04:30:34 am by Fungus »
 

Offline Fungus

  • Super Contributor
  • ***
  • Posts: 16561
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #53 on: March 20, 2018, 04:18:48 am »
That's a difference in syntax - and whatever benefits do or do not accrue - there is nothing functionally better in the executable.

The point is that there's something better in the source code.

Anyway, I'm not into the "this" is better than "that" head butting.  A lot of the time it is what people know that they champion.  There's no way to have a winner there.

Yep. The only reason somebody would champion C over C++ is that they don't really know C++.

(or that there's no decent C++ compiler available on their platform, although that argument doesn't really hold water any more - the C and C++ compilers are usually the same these days)
 
The following users thanked this post: alexanderbrevig

Offline Kjelt

  • Super Contributor
  • ***
  • Posts: 6459
  • Country: nl
Re: C++ for the Embedded Programmer
« Reply #54 on: March 20, 2018, 08:29:53 am »
Fact is C is still king in embedded software.
My new job they are only interested in my C skills since 80% of the machine was written in C and the youngplayers have problems. I don't care if I have to code C or C++, or Python or whatever.
Discussing whats better is useless.
On your job you encounter the one or the other or both and you have to deal with it, thats your job.

In 10 years we only do mdd and dont even know what compiler is used or code is coming out  :)

 

Offline apis

  • Super Contributor
  • ***
  • Posts: 1667
  • Country: se
  • Hobbyist
Re: C++ for the Embedded Programmer
« Reply #55 on: March 23, 2018, 12:37:36 pm »
C++ is more modern and has more features, no doubt about that. But C has several advantages that may not be obvious: It's more portable. It's simpler and therefore more predictable. That in turn means it's easier to prove it's standard compliant. It's easier to predict exactly what the assembly code will look like, and so on. Something you write in C today is likely to still compile fine in 10-20 years, but the same is less likely to be true for C++.
 

Offline Fungus

  • Super Contributor
  • ***
  • Posts: 16561
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #56 on: March 23, 2018, 02:05:31 pm »
But C has several advantages that may not be obvious: It's more portable. It's simpler and therefore more predictable. That in turn means it's easier to prove it's standard compliant. It's easier to predict exactly what the assembly code will look like, and so on.

I'm open to counter-examples but I'm not sure any of those are true unless you're only talking about legacy systems.

'Portability' these days usually means writing a code generator back-end for gcc. The same generator will be used by C and C++.

Something you write in C today is likely to still compile fine in 10-20 years, but the same is less likely to be true for C++.

That one's completely false.
 

Offline apis

  • Super Contributor
  • ***
  • Posts: 1667
  • Country: se
  • Hobbyist
Re: C++ for the Embedded Programmer
« Reply #57 on: March 23, 2018, 03:16:47 pm »
But C has several advantages that may not be obvious: It's more portable. It's simpler and therefore more predictable. That in turn means it's easier to prove it's standard compliant. It's easier to predict exactly what the assembly code will look like, and so on.
I'm open to counter-examples but I'm not sure any of those are true unless you're only talking about legacy systems.

'Portability' these days usually means writing a code generator back-end for gcc. The same generator will be used by C and C++.

Something you write in C today is likely to still compile fine in 10-20 years, but the same is less likely to be true for C++.

That one's completely false.

Often if you write complex software in C++ and using one compiler it will not even compile on another C++ compiler without modifications, and that have also been true with older compiler versions versus newer. Thus you can't expect code from 10-20 years ago to compile without problem on a modern version. I know projects that have been abandoned simply because the code was too old and it would be too much work to port it to a modern C++ compiler and libraries.

Would also like to see a C++ compiler that is provably standards compliant, something that is much easier to do with a C compiler (because the language is simpler), and that can be critical for sensitive applications.

With C you pretty much know what you get down to the machine code level and you can be pretty certain it will compile the same way in the future so it's easier to maintain.

I don't agree C++ is a horrible language like some people
( https://web.archive.org/web/20140706160843/http://thread.gmane.org/gmane.comp.version-control.git/57643/focus=57918 )
but sometimes C is the better choice. Especially if you want the most efficient and maintainable (predictable and portable) code.
« Last Edit: March 23, 2018, 05:18:19 pm by apis »
 

Offline Fungus

  • Super Contributor
  • ***
  • Posts: 16561
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #58 on: March 23, 2018, 03:44:22 pm »
Often if you write complex software in C++ and using one compiler it will not even compile on another C++ compiler without modifications, and that have also been true with older compiler versions versus newer. Thus you can't expect code from 10-20 years ago to compile without problem on a modern version.
It probably would if they'd followed the standard back when they wrote it.

The problem is that a lot of people made assumptions, eg. that iterators of std::vector were raw pointers and thus it was OK to assign values to them (eg. null). It may have worked on a particular compiler back in the day but it was never correct C++ code.

(I use that example because I've seen it and dealt with it in real life)

Yes, I know the C++ standard is larger than the C standard, but IMHO the most useful subset of C++ is about the same size.

Bjarne S. always said that "Inside C++ there's a smaller, cleaner language trying to get out".

I know projects that have been abandoned simply because the code was to old and it would be to much work to port it to a modern C++ compiler and libraries.

Sure, but the claim was "Something you write today..."  :popcorn:

With C you pretty much know what you get down to the machine code level and you can be pretty certain it will compile the same way in the future so it's easier to maintain.

My feelings are that C++ has settled down to the point where it's moot for new development.

(at least a decade ago, and certainly with C++ 0x11)
« Last Edit: March 23, 2018, 05:03:35 pm by Fungus »
 

Offline apis

  • Super Contributor
  • ***
  • Posts: 1667
  • Country: se
  • Hobbyist
Re: C++ for the Embedded Programmer
« Reply #59 on: March 23, 2018, 05:46:23 pm »
Sure, but the claim was "Something you write today..."  :popcorn:
Alright, I'll get back to you in 10-20 years time then. ;) I do like C++ but especially for embedded project that are often speed sensitive, operates at very low level, might have a lifetime of several decades, running on uncommon hardware, and often is more safety-critical than your average smartphone app; it often makes more sense to use C. I will not try to stop anyone from using whatever they want to use, I'm sure C++ is the better option in many applications. And now that I think about it, isn't there python for embedded applications as well these days? :D
 

Offline Fungus

  • Super Contributor
  • ***
  • Posts: 16561
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #60 on: March 23, 2018, 06:18:17 pm »
...often is more safety-critical than your average smartphone app; it often makes more sense to use C.

As noted earlier: Nobody would say that "operator+=" is essential but it makes things a little bit safer as well as easier.

The extra features of C++ don't just make coding easier, they make it a bit safer, too. Small details but it all adds up. Yes you can do it in C but the code is usually more verbose and requires more scrutiny.

If I was going to generalize this I'd say something like this: C++ allows you to move more of the code's complexity up into the library level. This makes the real program logic and layout much easier to work with (more transparent).

In C the logic part of the code is usually full of housekeeping/boilerplate code, eg. zeroing out structs before you can use them. Zeroing the struct is something the compiler should be doing, not the programmer. The zeroing just adds a little bit more clutter to the code and its one more thing that can be forgotten when you're having a bad hair day.

for embedded project that are often speed sensitive, operates at very low level...

(raises eyebrow)

Code written using a C++ compiler is necessarily slower or less low level than C?   ???

might have a lifetime of several decades, running on uncommon hardware

I don't have massive experience there but I doubt it'll make much difference if you're starting new code today. Is there a modern platform without a decent C++ compiler?
« Last Edit: March 23, 2018, 06:55:56 pm by Fungus »
 

Offline apis

  • Super Contributor
  • ***
  • Posts: 1667
  • Country: se
  • Hobbyist
Re: C++ for the Embedded Programmer
« Reply #61 on: March 23, 2018, 07:53:47 pm »
As noted earlier: Nobody would say that "operator+=" is essential but it makes things a little bit safer as well as easier.

The extra features of C++ don't just make coding easier, they make it a bit safer, too. Small details but it all adds up. Yes you can do it in C but the code is usually more verbose and requires more scrutiny.

If I was going to generalize this I'd say something like this: C++ allows you to move more of the code's complexity up into the library level. This makes the real program logic and layout much easier to work with (more transparent).

In C the logic part of the code is usually full of housekeeping/boilerplate code, eg. zeroing out structs before you can use them. Zeroing the struct is something the compiler should be doing, not the programmer. The zeroing just adds a little bit more clutter to the code and its one more thing that can be forgotten when you're having a bad hair day.
I see your point, and agree that for large complex project the oo features of C++ makes the code more readable and manageable and thus more secure in some ways. Here we are talking about embedded software though, which is typically much smaller and the benefits of oop is smaller. The reason C has an edge here imho is that you have finer control over what machine code is generated. Yes, in C++ the compiler does more for you, but that also means there are more things that can go wrong. For example, if you are forced to switch compiler to another version or maybe even platform and model of the compiler, then you can no longer be certain it will generate exactly the same machine code (or at least it would be a lot harder). And for embedded systems that relies on real time timing and such, that might be enough to break it, and it will be a real headache to debug.

for embedded project that are often speed sensitive, operates at very low level...

(raises eyebrow)

Code written using a C++ compiler is necessarily slower or less low level than C?   ???
C is a lower level language than C++ since you let the compiler do more of the work for you, and C++ will generate automatic crap that isn't always necessary (for most non embedded applications the difference is negligible though). And if you rely on lots of library feature it just gets worse, aaand it's not just speed that is important, codesize is also important for example.

might have a lifetime of several decades, running on uncommon hardware

I don't have massive experience there but I doubt it'll make much difference if you're starting new code today. Is there a modern platform without a decent C++ compiler?
Yes, there isn't a C++ compiler for all the pic micros for example.
 

Offline Karel

  • Super Contributor
  • ***
  • Posts: 2214
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #62 on: March 23, 2018, 08:32:01 pm »
Popularity of programming languages (in general, not just embedded):

1   Java   14.941%
2   C   12.760%
3   C++   6.452%
4   Python   5.869%
5   C#   5.067%

https://www.tiobe.com/tiobe-index/
 

Offline Fungus

  • Super Contributor
  • ***
  • Posts: 16561
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #63 on: March 23, 2018, 08:54:03 pm »
Popularity of programming languages (in general, not just embedded):

1   Java   14.941%
2   C   12.760%
3   C++   6.452%
4   Python   5.869%
5   C#   5.067%


Usage != enjoyment

(or best)
 

Offline Karel

  • Super Contributor
  • ***
  • Posts: 2214
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #64 on: March 23, 2018, 09:01:59 pm »
Popularity of programming languages (in general, not just embedded):

1   Java   14.941%
2   C   12.760%
3   C++   6.452%
4   Python   5.869%
5   C#   5.067%


Usage != enjoyment

(or best)

The survey is about popularity, not usage.

popularity: the state or condition of being liked, admired, or supported by many people.

 

Offline Fungus

  • Super Contributor
  • ***
  • Posts: 16561
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #65 on: March 23, 2018, 09:14:44 pm »
The survey is about popularity, not usage.

Nope.

The page itself tells you how those numbers are calculated:

Quote
Basically the calculation comes down to counting hits for the search query

+"<language> programming"

It could be that Java is #1 because Java causes the most problems (and therefore the most number of pages dedicated to solving them).

Or maybe Java is #1 because it's almost obligatory at enterprise level (and therefore the most number of expensive consultants are after that money).

 

Offline KX36

  • Contributor
  • Posts: 16
  • Country: gb
Re: C++ for the Embedded Programmer
« Reply #66 on: April 03, 2018, 08:21:45 pm »
If I may stick my newbie head above the parapet for a second and ask a question about the code in the video...

This Pin class template.. Class templates aren't classes themselves, they generate classes from the template right? So does that mean a new class is generated for each combination of port and pin, or is that not the case because the port and pin template parameters are non-type parameters so since they are always the same type it only generates the class once, or something else?

I've been trying to implement my own Pin class template as I like the idea. I've put a static member variable in it and that is definitely generated once for each combination of template parameters (as seen by the size program) If I make 2 objects with the same port and pin it doesn't generate the variable again, which leads me to think a new class is generated for each combination of port and pin template parameters. (For my template parameters, Port is an enum, pin is a char.)

Cheers
« Last Edit: April 03, 2018, 09:12:47 pm by KX36 »
 

Offline Fungus

  • Super Contributor
  • ***
  • Posts: 16561
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #67 on: April 03, 2018, 09:14:56 pm »
If I may stick my newbie head above the parapet for a second and ask a question about the code in the video...

This Pin class template.. Class templates aren't classes themselves, they generate classes from the template right? So does that mean a new class is generated for each combination of port and pin,

Yes, but if you do it right the compiler will inline everything and optimize the pin changes all the way down to a single machine-code instruction.
« Last Edit: April 04, 2018, 12:09:16 am by Fungus »
 

Offline Karel

  • Super Contributor
  • ***
  • Posts: 2214
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #68 on: April 04, 2018, 06:29:59 am »
The survey is about popularity, not usage.

Nope.

The page itself tells you how those numbers are calculated:

Quote
Basically the calculation comes down to counting hits for the search query

+"<language> programming"

It could be that Java is #1 because Java causes the most problems (and therefore the most number of pages dedicated to solving them).

Or maybe Java is #1 because it's almost obligatory at enterprise level (and therefore the most number of expensive consultants are after that money).

A bit like why windows is most used on the desktop, not because it works better?
 

Offline AlfBaz

  • Super Contributor
  • ***
  • Posts: 2183
  • Country: au
Re: C++ for the Embedded Programmer
« Reply #69 on: April 05, 2018, 01:10:50 am »
If I may stick my newbie head above the parapet for a second and ask a question about the code in the video...

This Pin class template.. Class templates aren't classes themselves, they generate classes from the template right? So does that mean a new class is generated for each combination of port and pin,

Yes, but if you do it right the compiler will inline everything and optimize the pin changes all the way down to a single machine-code instruction.
Settle down mate. I'm looking through the arm instruction set and nowhere do I see an instruction that takes a collection of bit patterns and stores them into several different, selectable locations.
The beast we are taming is a complex, feature laden micro that requires a lot of peeking and poking to get the job done. Putting together a reusable HLL construct in any language is going to take a significant amount of work not matter what language you use
 

Offline Fungus

  • Super Contributor
  • ***
  • Posts: 16561
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #70 on: April 05, 2018, 08:44:42 am »
If I may stick my newbie head above the parapet for a second and ask a question about the code in the video...

This Pin class template.. Class templates aren't classes themselves, they generate classes from the template right? So does that mean a new class is generated for each combination of port and pin,

Yes, but if you do it right the compiler will inline everything and optimize the pin changes all the way down to a single machine-code instruction.
Settle down mate. I'm looking through the arm instruction set and nowhere do I see an instruction that takes a collection of bit patterns and stores them into several different, selectable locations.

I mean each individual pin change, not a whole list of pin changes, obviously.

The point I was making was that it doesn't matter if "a new class is generated for each combination of port and pin", the compiler can optimize all that away (and does so - I've checked several times).

The reason I'm being so deliberate about replying to this point is because a lot of this topic has been C programmers imagining C++ bloat. Statements like "a new class is generated for each combination of port and pin" are bound to unsettle them.
 

Offline AlfBaz

  • Super Contributor
  • ***
  • Posts: 2183
  • Country: au
Re: C++ for the Embedded Programmer
« Reply #71 on: April 05, 2018, 03:05:53 pm »
The reason I'm being so deliberate about replying to this point is because a lot of this topic has been C programmers imagining C++ bloat. Statements like "a new class is generated for each combination of port and pin" are bound to unsettle them.
I keep seeing the phrase "If you do it right" when it comes to c++ on embedded platforms. How deep into c++ compiler theory do you need to go to avoid doing it wrong?
Don't get me wrong, I like c++ features and have used it PC's but I've never bothered with compiler output there
 
The following users thanked this post: Frank

Offline Fungus

  • Super Contributor
  • ***
  • Posts: 16561
  • Country: 00
Re: C++ for the Embedded Programmer
« Reply #72 on: April 05, 2018, 05:45:15 pm »
The reason I'm being so deliberate about replying to this point is because a lot of this topic has been C programmers imagining C++ bloat. Statements like "a new class is generated for each combination of port and pin" are bound to unsettle them.
I keep seeing the phrase "If you do it right" when it comes to c++ on embedded platforms. How deep into c++ compiler theory do you need to go to avoid doing it wrong?
Don't get me wrong, I like c++ features and have used it PC's but I've never bothered with compiler output there

Good question.

A better question might be, "What do you have to do to make it go wrong?". I don't know the answer offhand but I suspect it won't be easy.

I do know that compilers are amazingly good at reducing constant expressions down to the result value.

eg. This:

float x = (sqrt(2.0)<1.0)? sqrt(sin(1.0)): tan(acos(0.5));
byte y = *(byte*)&x;


Will reduce down to this:

byte y = 0xd8;

(I just tried it on the Arduino compiler, it really does that...!)


Moral: Don't worry too much about the compiler optimizing away a few bitwise operators in templates.
« Last Edit: April 05, 2018, 06:24:20 pm by Fungus »
 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 895
  • Country: us
Re: C++ for the Embedded Programmer
« Reply #73 on: April 05, 2018, 06:59:52 pm »
Moral: Don't worry too much about the compiler optimizing away a few bitwise operators in templates.
I think you should worry, or at least be aware of what the compiler's going to do.

In particular, if you're going to instantiate a template multiple times, it's basically the same as copy-n-paste. You don't have to maintain all the generated source, but the compiler and linker need to deal with the resulting object code just as if you typed it all in yourself.

So, for instance, you wouldn't want to put "big" methods (i.e., with lots of compiled code) in the template. Factor those out into a base class and have your template only deal with what's necessary to distinguish the instances. Don't put static variables in the template unless you really need one per instantiated class.

I use C++ for my GPIO pins too, but not with templates. Generally speaking, I don't care about ultimate speed or minimum code size, I want a higher level interface to what a "pin" is that I can pass around (usually by reference) to other modules that need GPIO to get work done. E.g., a SPI slave might need a chip select pin.

 

Offline JS

  • Frequent Contributor
  • **
  • Posts: 947
  • Country: ar
Re: C++ for the Embedded Programmer
« Reply #74 on: April 27, 2018, 06:38:40 pm »
Can I ask a question and you help me?

  I've just started to play around with some STM32 (I bought a few bluepills and a discovery) and after a few days I have the setup running for C, STM32CubeMX to generate the projects including FreeRTOS, SW4STM32 IDE (On OSX) and ST programer to load the bin files to the board.

  Now the question, how do I go from this to C++? I don't have any against it (just know less C++ than C but I guess that is solved with time) My question is about the programming environment, how to set up C++ IDE, libraries to get it up and running, an RTOS, etc. Getting it to work with C was ok for me, it did took some time to get all running on OSX but it's running.

JS
If I don't know how it works, I prefer not to turn it on.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf