c vs cpp for stm32 - Page 1
Forum section: electronics / general

author: bogdant
author_rank: Regular Contributor
timestamp: January 11, 2019, 07:09:15 am
content: Does it make any sense to switch from c to c++? I tried to configure system workbench stm32 to convert a project from C to C++ but this is not trivial. Even it does compile on the target when it try to call contructor gives a hard fault.Sent from my VTR-L29 using Tapatalk

author: westfw
author_rank: Super Contributor
timestamp: January 11, 2019, 09:06:48 am
content: QuoteYes.QuoteIt SHOULD be trivial. See the Arduino Environment, for example. Vanilla C should compile fine with C++, and immediately give you useful features like function overloading and better type checking.Just because you've switched to C++ doesn't mean you can go wild with STL and dynamic memory allocation, though (some would argue that therefore, "it isnt' really C++")

author: shangaoren
author_rank: Regular Contributor
timestamp: January 11, 2019, 02:45:08 pm
content: Try atollic instead of system Workbench, this is the new tool of ST Microelectronics and this is better than system workbench.It's not easy to convert a project, i suggest you to start an another and copy/paste your files instead.If you do a project in c++ you will not want to do C anymore

author: cv007
author_rank: Frequent Contributor
timestamp: January 11, 2019, 05:12:33 pm
content: Yes it makes sense. You end up with code that is easier to read (for you and everyone else) and write, easier to use, and probably less prone to errors as a result. It doesn't even require the use of many c++ features to see the benefits. The size of the compiled code will tell you when its not a good idea to use a particular c++ feature, so its not difficult to stay away from the 'heavy' parts.If your micro of choice has an available c++ compiler, take advantage of it.

author: twiddle
author_rank: Contributor
timestamp: January 11, 2019, 10:45:34 pm
content: Double check your linker script and startup code integrate properly with the C++ runtime.I'm not on my dev machine at the moment but I'm quite certain my linker script had to add additional sections to store constructors for static objects and so on, and startup code to call those constructors during runtime initialization - at a guess I'd say your hard fault is possibly related.I've been using C++ on STM32 chips for a few years without issues now - I'm actually working on a 'pure' C++ framework that provides a type-safe and zero-cost alternative to the CMSIS headers etc, so it definitely is possible to do and can provide benefits, if you avoid most of the STL and dynamic allocation.

author: cv007
author_rank: Frequent Contributor
timestamp: January 12, 2019, 02:27:56 am
content: QuoteIn addition, it could also be you are not getting the compiler options set for g++, like a missing -mthumb for example would end up producing 32bit code I think, and get you an exception. If you can get your build environment to show the command output when compiling you could at least see what options are making it to the compiler.this folder has a simple c++ app, and is pretty bare-https://github.com/cv007/Samd10XplainedMinibut maybe the linker script and startup file has some info that could helpit looks like __libc_init_array() called from the startup file does the c++ init work, and about a quarter of the linker script deals with c++ it seems

author: Nerull
author_rank: Frequent Contributor
timestamp: January 12, 2019, 03:23:01 am
content: Quote from: westfw on January 11, 2019, 09:06:48 amNot all valid C code is valid C++ code, for example unions are commonly used in C microcontroller APIs for type punning of registers, but this is undefined behavior in C++ - only the last assigned member of a union should be accessed, and compilers are free to pack variables in ways that make the behavior unpredictable.How strictly any given compiler enforces the difference between the standards is another question. GCC does support using unions this way via a compiler extension.

author: bogdant
author_rank: Regular Contributor
timestamp: January 12, 2019, 07:45:26 am
content: thank you all for help. I will try.Sent from my VTR-L29 using Tapatalk

author: rhb
author_rank: Super Contributor
timestamp: January 12, 2019, 10:11:13 pm
content: Each object in C++ consists of a structure containing all the public and private variables *and* pointers to all the methods applicable to the class. That consumes quite a lot of memory.As for readability, that is *entirely* a function of whether the author attempted to write readable code. If you encounter something such as:{ new A a;new B b;new C c;d = a + b + c;}you may need to read a *lot* of code to find out what that assignment does. And if *any* of the classes use multiple inheritance you'll also need to read the compiler implementation notes and the C++ standard. If you're using g++ you may not be able to find out what happens except by single stepping at assembly level. For extra entertainment, it may be different with the next release of the compiler.The difference between C and C++ is purely syntactic. There is nothing that can be done in C++ that can't be done in C.Twenty years ago I wrote a string substitution module which given a character string returned another character string in C and in C++. It had functions to insert and remove string pairs and to convert them. The C version was a 1/2 page. The C++ version was 3 pages. All done in the best style as advocated by Meyers, Lakos, Cargill and other authors. That was the last time I wrote anything in C++.The 3-4 ft of books on OOP and C++ are the least used books in my library by far. I don't ever use C++ unless I'm modifying an existing C++ code. And that is something I try to avoid.A major virtue of C is that it is easy to understand what the hardware does when it executes a statement. That is not true of C++. In 20+ years I've not encountered a C++ enthusiast who actually understood at the HW level what their code actually did.On the job where I wrote the string substitution, I had posted a page from Lakos on linking large C++ projects on my door. It was generally ignored until 6 months later when compiles started taking massive amounts of time. It took a team of 4-5 C++ programmers 6 weeks to fix the mess they had made. But one of them had paid attention to the post on my door and pulled a copy out of his desk drawer when they hard to rearchitect the mess.One of my side functions throughout my career was explaining the nuances of various languages (mostly C & FORTRAN) and the compiling, linking and execution phase processes to a host of coworkers. And I started most of my jobs making 500,000+ lines of someone else's code compilable just to be able to actually do what I'd been hired to do.

author: andersm
author_rank: Super Contributor
timestamp: January 12, 2019, 10:31:39 pm
content: Quote from: rhb on January 12, 2019, 10:11:13 pmAll C++ compilers I know use some form ofvirtual method table. Vtables are also only used if the class has virtual functions, since they're not needed for static dispatch.QuoteThat hasn't been true since at least C++11.

author: 17_29bis
author_rank: Regular Contributor
timestamp: January 12, 2019, 11:18:14 pm
content: Quote from: shangaoren on January 11, 2019, 02:45:08 pmIt would be really great to hear why is that. Could you please share with us what projects you have done in C++ (for MCU, specifically the ones that could not be done in C) and how C++ helped you in those cases? No, seriously

author: rhb
author_rank: Super Contributor
timestamp: January 13, 2019, 01:09:38 am
content: Quote from: andersm on January 12, 2019, 10:31:39 pmAs the proof you are wrong is almost 80 years old I think I'll let you argue with Alan Turing.

author: cv007
author_rank: Frequent Contributor
timestamp: January 13, 2019, 03:06:48 am
content: QuoteThere is nothing that can be done in C than cannot also be done in assembly. I assume you don't program in assembly. The same applies to C++. You pick a language because its easier/more reliable/better in some way than any previous language you were using.I'm sure there were (or still are a few) assembly language programmers who said they would never use c for any number of reasons (too bloated, too slow, not necessary, I lose control, I can create better code, etc.)., but in most cases you would now say they are silly to not make use of a c compiler. To some degree c++ vs c is somewhat the same- if you have a c++ compiler available why not at least check it out, it may make your job/hobby easier or more enjoyable.QuoteI think a lot has changed in 20 years.I probably should not be showing my code because maybe I'm doing it all wrong-https://github.com/cv007/PIC32MM_Curiosity_CPP/blob/master/cable_test.cppbut I like how easy things become in c++, and this was a simple cable tester I needed quickly and was quickly made(I previously wrote all the 'drivers' for the pic32mm in c++, so had everything in place- you are only one header or source file away from seeing the source, which I think is readable and as close to the hardware as c, I also wrote the usb 'driver' in c++)you could argue that everything could be done in c, and you would be right, just as it could also be done in assembly, but I find I can organize code much better, don't have to struggle with coming up with function names, and generally end up with much better/more reliable code that I find much easier to read and write.I also am able to apply any c++ skills I have accumulated to other things- arduino-esp32, various pc code, and simply being able to read code from projects I'm interested in that happen to use c++.It sure looks like I wrote too much

author: hans
author_rank: Super Contributor
timestamp: January 13, 2019, 09:02:03 am
content: Quote from: rhb on January 13, 2019, 01:09:38 amStuff you can dowithC/C++ sure.Stuff you can doinC++ is so much powerful. Templates is very flexible. There is better support for compile-time expressions for your project using constexpr.

author: rhb
author_rank: Super Contributor
timestamp: January 13, 2019, 02:03:28 pm
content: In SunOS 4.1.1 an xclock display consumed a few KB of memory. On OpenIndiana Hipster running Mate, the same display consumes 80 MB. The reason for the fantastic bloat is OOP frameworks. I did a *lot* of DSP on *time shared* VAXen with 4 or 5 MB of DRAM over the course 4 years. And probably worked another 10 years before I had a system with more than 64 MB of core. I worked in the oil industry and usually had the latest workstation. Though I did demand my old system back when I found a new workstation on my desk after I returned from a few days off.You can't run Firefox on a machine with less than 4 GB of DRAM today. We used to know exactly what the machine did, but now no one knows.C is not C++. C/C++ is head hunter speak.Try debugging 500,000 lines of C++ code you've never seen before and which has no documentation or internal comments other than the author's name. Try setting a few breakpoints at the entry to some functions. If you don't a priori know the names of the methods called in the constructors of the parent classes you are going to spend a lot of time researching the parent classes. That gets really tedious if all you have are header files and libraries.Can it be done? Yes. But is is *very* time consuming and absolutely necessary if the problem is a failure of a constructor to properly initialize an object. If the bug is 4-5 layers deep in the inheritance tree it will take a lot of work to fix.

author: NorthGuy
author_rank: Super Contributor
timestamp: January 13, 2019, 02:48:13 pm
content: Quote from: bogdant on January 11, 2019, 07:09:15 amIf you feel it is better to implement your design in C, do it in C. If you feel it is better to implement your design in C++, do it in C++. Either choice will not improve your design. It is merely a matter of convenience to you. Of course, other people cannot tell you what is more convenient to you.If you don't see the difference (and if you're asking you probably don't), then there's no reason to waste time and efforts on switching.

author: Yansi
author_rank: Super Contributor
timestamp: January 13, 2019, 03:48:51 pm
content: Convenience to you, but inconvenience for anybody else, who will try to fix your C++ gibberish, hi hi!

author: SiliconWizard
author_rank: Super Contributor
timestamp: January 13, 2019, 04:41:14 pm
content: Quote from: rhb on January 13, 2019, 02:03:28 pmCould not agree more.

author: IDEngineer
author_rank: Super Contributor
timestamp: January 13, 2019, 06:29:36 pm
content: Oh boy, this argument again! Apparently I can get my annual rant on this topic out of the way nice and early in 2019.Folks need to remember that C is, essentially, a portable Assembly language. It was designed and intended to be a "mid-level" language, trading a bit of Assembly's efficiency for portability across platforms. There's a lot of value in that tradeoff, because it allows the investment in debugged code to be migrated to different/new hardware/OS environments. And the industry has responded, resulting in some processors having their instruction sets specifically optimized for C language constructs - making it easier for compilers to generate efficient code from C source.But, as with virtually every discipline (hardware, software, mechanical, even the design of governments [I'm thinking of you, US Constitution]), when you insist on glomming a bunch of later features that go way beyond the scope of the original intent, you get "spaghetti code". The glommed-on features are usually poorly implemented and awkward to use. Meanwhile, they often conflict with the original architecture and interfere with some/all of the original features. A nice lose-lose arrangement.Consider two examples:1) C++. I'm sorry, but the best feature of C++ is its // comment operator so you don't have to terminate comments with */. If you don't hate C++, you haven't debugged something like overloaded functions written by strangers you've never met. In what universe is it a good idea to have multiple entities share the exact same name? A call to an overloaded function name means you don't really know where your code is going. Good luck if those overloaded functions are in some library for which you don't have the source. And I can't imagine a sufficiently painful punishment for whomever added dynamic polymorphism, where you literally don't know and may not even be able to predict what functions will be called when, now or in the future! I realize this sort of thing replaces normal sexual excitement for Computer Science postdocs, but in the real world these sorts of language "features" literally enable bugs and exploits that are hideously difficult to find and fix. I can't prove this, but after lots of conversations I'm convinced that the obtuseness and opacity of environments like C++ cause Engineers to just throw up their hands and declare something "done" because there's simply not the time nor money nor management support to find and test the edge cases. And C++ *creates* such edge cases, as when user input can basically randomize your execution path (choice of called function dependent upon what the user types now/today/next week). It's entirely possible that the first "real user" will invoke function(s) never before called during alpha and beta testing, with unknown and untested results. Insanity! C++ insures perpetual profitability for the antivirus industry.2) Java. Sort-of-C, sort-of-C++, with yet another layer Rube Goldberged into the mess. Every time you turn around there's another weird special case that is painfully and obviously due to the effort to add something that doesn't quite "fit" with the base language. I'll admit functions like BigDecimal() are handy, but there's nothing Java-specific about that. If Object Orientedness is the goal, use a language designed from the ground up with that in mind. There's no shortage of them out there... why hobble yourself with some hybrid, bastardized FrankenLanguage like Java?I'm sure I've offended some folks with the above. But after ~40 years of writing software and firmware in all sorts of OS and embedded environments, these are my conclusions. Yours may vary, and that's fine, but I've reached the point in my career where I can turn down projects that are artificially handicapped because someone demands we use their favorite OO-hybrid language to implement an LED flasher. Wrangling projects to successful completion is hard enough without intentionally lashing oneself to such an anchor. Tools are supposed to make jobs EASIER, not more difficult.Just my $0.02, and worth no more than you paid for it! {grin}

author: Yansi
author_rank: Super Contributor
timestamp: January 13, 2019, 06:45:50 pm
content: Quote from: IDEngineer on January 13, 2019, 06:29:36 pmYou seem you haven't programmed in C much if at all, have you? Otherwise you would not argue that // comment is the feature of C++.//EDIT: OK, I know it was introduced with the C++, but it does not limit you to use this only in C++ these days. C compilers understand that well, that's what I meant by the comment above. I would not list that as a feature why C++ should be used instead of C. That simply I think is invalid argument. Otherwise I acknowledge your points stated and add myself to the crowd of C++, C# and Java haters.

author: SiliconWizard
author_rank: Super Contributor
timestamp: January 13, 2019, 07:00:48 pm
content: Quote from: Yansi on January 13, 2019, 06:45:50 pmAlthough a very anecdotical point in IDEngineer's post, the // comment in C has actually been officially introduced in the C99 standard. Before that, it was not standard C (although many C compilers had already added this, but that was an unofficial extension) and thus, only an official "feature" of C++. I guess that was his point and was kind of ironic too. You could argue that C99 is 20 years old already, but actually only a very few C compilers were C99 compliant until only just a few years ago (the fact most of them supported the // was again not the sign of any kind of compliance).The rest of IDEngineer's arguments were more interesting that this humourous sentence.

author: Yansi
author_rank: Super Contributor
timestamp: January 13, 2019, 07:09:15 pm
content: Well I do not know if this is anecdotical or not, but I would not argue about the comment style in any way. (After all, I prefer the /**/ style of comments, they look better)

author: IDEngineer
author_rank: Super Contributor
timestamp: January 13, 2019, 07:22:49 pm
content: Quote from: SiliconWizard on January 13, 2019, 07:00:48 pmThank you! I presumed your comments were common knowledge, but apparently not.There's a reason /**/ is called "C Style" and // is called "C++ Style". First hit on Google:Quote

author: bogdant
author_rank: Regular Contributor
timestamp: January 13, 2019, 07:24:59 pm
content: So there are pro and cons for c++. When starting a new project on a powerfull stm32f7xx series microcontroller do you consider C++? Do you try to reuse code from PC world to micro?Sent from my VTR-L29 using Tapatalk

author: IDEngineer
author_rank: Super Contributor
timestamp: January 13, 2019, 07:28:56 pm
content: Quote from: Yansi on January 13, 2019, 06:45:50 pmI agree, which is why I didn't say that. Let's review:QuoteI didn't say // was "why C++ should be used instead of C". I said // was the best feature of C++ (which doubled as a backhanded insult against all of the other glop that C++ added to C). And, as SiliconWizard pointed out, // was such a good feature that it was formally added to the C99 standard. Which reinforces my point!

author: bogdant
author_rank: Regular Contributor
timestamp: January 13, 2019, 07:41:19 pm
content: Quote from: IDEngineer on January 13, 2019, 06:29:36 pmCan you tell as in OS you have worked, is it used the C++,? I know in Linux kernel, C is used.Sent from my VTR-L29 using Tapatalk

author: Yansi
author_rank: Super Contributor
timestamp: January 13, 2019, 07:44:30 pm
content: Quote from: bogdant on January 13, 2019, 07:24:59 pmNot even remotely considering C++. Most things in real world even can't be written in it, due to safety concerns of the C++ being less predictable and harder to be statically analyzed for possible errors.STM32F7 can be written in C no problems.And yes, I have used some interesting pieces of "PC code" in them, for example have ported the Nuklear graphics library in there.https://github.com/vurtun/nuklearWasn't even complicated, I have even let it do it's magic with dynamic allocation, haven't bothered to reconfigure the examples provided. Have worked absolutely fine.

author: rhb
author_rank: Super Contributor
timestamp: January 13, 2019, 11:06:53 pm
content: My experience working on several million lines of other people's code is that old C & FORTRAN codes can be fixed even if there is no documentation or comments if you understand what they do. It can be painful if you have to read a professional paper to determine if the calculation is being done in the time or frequency domain, but it can be done.The two old C++ codes I was asked to look at could not even be compiled. In one instance the developer had deleted all his files when he was laid off and put a logic bomb in the code. I had his machine and account restored from backups but even with his command line history and environment I couldn't get it to compile. The command line history suggested that he had great difficulty compiling it himself.Fortunately the logic bomb used system( "date" ) to get the date for triggering the logic bomb. So I just put a wrapper around the program that used a one line shell script to lie about the date. That bought me time to find a commercial replacement.The other instance, the code was so old that no C++ compiler would accept it. I tried quite a few, but there was either no extant executable or it had been stripped so I couldn't identify what that author had used. I did work out that it was written before the C++ standard was ratified using some version of g++, but that was all.

author: ehughes
author_rank: Frequent Contributor
timestamp: January 13, 2019, 11:28:08 pm
content: For me it is pretty easy, always C. By the time I need the abstractions that c++ provides, I find that there are other high level languages that do it better and offer real memory safety, etc.For most embedded work I have never seen the need for reuse that c++ claims to offers. Virtually all embedded systems require integration between the software pieces and the idea that you will ever wholesale reuse something without modification is dumb. It is a waste of time abstracting everything.I was once told to use c++ for the Lambda's. It looked like the dumbest idea ever for embedded code.I was also shown (by a CMU professor at a conference) that C++ can overlay objects on memory mapped peripherals. It was the ugliest boiler plate I have ever seen for initializing a UART. He claimed you will never make a mistake using of using signed int pointer for a peripheral registers. Seemed like a lot of work for software purity.I honestly find myself wanted to go the other way. If I want to write cryptic code, I'll just do it nice and tight in asm.

author: 17_29bis
author_rank: Regular Contributor
timestamp: January 14, 2019, 12:52:44 am
content: Quote from: cv007 on January 13, 2019, 03:06:48 amThe question was actually for a different user but hearing different opinions is always good. As far as I am concerned I know Assembler, C, C++, Python and have been doing contract work using those languages for years. The reason why I asked the question what I asked is simple. There are different projects, some can be implemented/written (more or less) in any computer language, some require specific language and some may benefit from using a particular computer language more then other etc.My 0.3 cents: main difference between C++ and C is that C is a procedural language and C++ is all about OOP (Object Oriented Programming). If your project does not require OOP when why invent a square wheel? if you know Assembler, C - use it and it will pay off in a form of more easy support and debugging, otherwise you still can use C++ and get the job done. If your project does require OOP then I would say - try to study C++ instead of developing the code in C (which is also possible to some extended but it will require enormous efforts).PS: looks like I simply restated in my own language what cv007 said above in his last sentence.

author: IDEngineer
author_rank: Super Contributor
timestamp: January 14, 2019, 01:00:48 am
content: Quote from: ehughes on January 13, 2019, 11:28:08 pmSounds very familiar, right in line with my comment about CS postdocs above. Those guys get sweaty palms about this stuff, but in the real world of actually shipping products the "purity" of it all matters less than getting it done and knowing it's correct.I didn't make up that "sweaty palms" comment, by the way. That's adirect quote, describing himself, from a CS professor who came to teach an OO class at one of my former employers who had been convinced by the local university that OO was the future. Their team of Project Engineers, of which I was one, sat through about the first week of his classes and then informed management they could have OO only if they were willing to double every development schedule going forward to accommodate this latest fad d'jour. The class ended abruptly soon after. It was valuable, though, for revealing the true motivation behind OO for some of these people. AFAIK this professor (who was a very nice individual, BTW) had never shipped an actual product in his life, so he and his fellows could afford to wallow in the latest craze getting their [insert body part here] sweaty. Meanwhile, we were writing embedded firmware in C and Assembly, languages which are broadly supported on virtually every platform and which are generally the very first (and sometimes only!) languages to be supported on new hardware. True then, true today.

author: Mattjd
author_rank: Regular Contributor
timestamp: January 14, 2019, 01:29:59 am
content: a lot of you guys keep saying C++ and java (more C++) dont get used in deployment code but I work for one of the largest defense contractors in the world and I can tell you that after my department is done (the modeling and simulations part) the deployment is done in C++ and java.So, what are you guys talking about? Or are you just painting broad strokes?

author: bson
author_rank: Unknown
timestamp: January 14, 2019, 02:22:39 am
content: Quote from: twiddle on January 11, 2019, 10:45:34 pmThat's not really true anymore for the gcc toolchain; it uses the static initializer list for things like initializing the data segment from flash. These used to have a separate table, but it's now unified. In the process, the .ctor.* and .dtor.* (I may misremember the exact prefix used) also disappeared and there is now a single static initializer. As a result, neither the linker script verbage to collect and emit the list (which must be a pure section) or the code to walk the list is optional. If you don't use ANY standard library you need to provide it yourself and make sure it gets called early, or your data segment will be uninitialized prior to reaching main(). Of course, the destructor lists don't need to be kept, since firmware isn't a normal program that will ever exit, so no need to keep things like destructors for global objects.Code:// In a compiler specific header// #define __weak gnu::weak[] extern void (*__preinit_array_start []) (void);[] extern void (*__preinit_array_end []) (void);[] extern void (*__init_array_start []) (void);[] extern void (*__init_array_end []) (void);void init_array() {size_t count, i;count = __preinit_array_end - __preinit_array_start;for (i = 0; i < count; i++)__preinit_array_start();count = __init_array_end - __init_array_start;for (i = 0; i < count; i++)__init_array_start();}

author: andyturk
author_rank: Frequent Contributor
timestamp: January 14, 2019, 04:06:14 am
content: GCC's linker generates a function to do all the static initialization:__libc_init_array(). I don't rely on static initialization these days, but still include a call to it in Cortex-M reset handlers:Code:#include <cstdint>extern "C" {extern uint32_t __etext;extern uint32_t __data_start__;extern uint32_t __data_end__;extern uint32_t __bss_start__;extern uint32_t __bss_end__;extern int main();extern void SystemInit();extern void __libc_init_array();void Reset_Handler() {SystemInit();uint32_t *src = &__etext;uint32_t *dst = &__data_start__;uint32_t *lim = &__data_end__;while (dst < lim) { *dst++ = *src++; }dst = &__bss_start__;lim = &__bss_end__;while (dst < lim) { *dst++ = 0; }__libc_init_array();main();}} // extern "C"

author: bogdant
author_rank: Regular Contributor
timestamp: January 14, 2019, 06:29:02 am
content: Is there a way to evaluate an micro based project needs OOP?

author: Berni
author_rank: Super Contributor
timestamp: January 14, 2019, 06:35:33 am
content: Yeah i like to stick to C. I do like some of the extra features that C++ provides but i never end up using any of the more advanced stuff such as lamba functions and just stick to classes and overlays.Object oriented programming is not all bad, the problem is that programmers take the idea way too far. They are often taught straight C++ without showing them C or assembler beforehand so they have no idea whats going on under the hood. Then the go and make classes for every little thing you could think of, inherit them 10 levels deep, give them confusing names, use factories to create them etc.. Its mostly the programmers fault for why C++ code tends to become messier than C code even tho object oriented programing is supposed to make cleaner code. For the rare times you want class like behavior in C you can use a struct and pointers to do pretty much the same thing (It looks a bit worse tho).But just because you stick to C doesn't mean you can't make a tangled mess of code. The STM32 HAL libraries are a good example of it. The thing was clearly made by a C++ programmer that was forced to use C by there boss. There are so many structures everywhere for no reason, #includes drag in all sorts of crap. The #define macros used nest other defines inside of them over 5 layers deep, these defines are scattered all over a pile of .h files. Its a real puzzle combined with a cat and mouse chase to find out what one of these #define actually does (And they use a lot of fancy tricks too so you better be sharp on your operators and pointer tricks). It should not be this difficult to figure out how a damn UART or GPIO driver works. To add insult to injury the HAL drivers sometimes don't work so you have to actually go and debug this mess, or sometimes the driver is designed for a weird use case where you need to actually modify it to make it do what you need.(Like the UART driver can't continuously receive or the I2C driver can't generate a bus restart condition)Here is an example how a C++ programmer can turn a perfectly sensible piece of code into object oriented shit:

author: Vasi
author_rank: Regular Contributor
timestamp: January 14, 2019, 06:42:46 am
content: The target is not the language. And you are not tied to that. If you are asked to do a job, you do it based on your knowledge. And the result can be brilliant of very poor, no matter the language used.

author: Nominal Animal
author_rank: Super Contributor
timestamp: January 14, 2019, 07:40:55 am
content: Quote from: bogdant on January 11, 2019, 07:09:15 amIt makes exactly as much sense as switching from German to French.If you live in France (say, intend to use existing Arduino code), then yes. If you live in Germany (say, have a large C codebase), then probably not.It is a good idea tolearnnew programming languages, at least to the point that you can solve typical problems for that language using robust, clean, easily maintained code.The reason for that is that tool choice affects how the maker thinks. I believe that most (good?) programmers eventually think in an internal non-verbal language they use to manage the inherent complexity in large software projects. Learning different programming languages (and the more different, the better; consider exploring Haskell and Lisp, if only to see if you can grasp how they could be useful) allows a better "vocabulary" for that internal language. C and C++ are too close to reallyforceone to understand their differences. It is like being an orange farmer, and being asked to describe a lemon, or how a lemon differs from an orange. Or maybe a lime and lemon, I dunno. Fruits all the way.I used to write user interfaces in C++, but I seem to have shifted to Python for that. (The biggest reason for that is probably that I like having the user interface user-modifiable without recompilation or having a development environment.) The object-oriented paradigm is perfectly suited for those.I use C for low-level libraries and high-performance computing core routines, as writing them in assembly would be too slow. (I can do that too, though; it is just that outside of SIMD vectorization, current C compilers typically find optimization opportunities at the machine code level I would miss. For critical code, I still do some inline assembly, but even for those, I tend to start by looking at different variations generated by a C compiler, then try to better that.)For microcontrollers, I use a strict imperative subset of C++; no exceptions, and objects more like syntactic sugar used to keep the code modular.For microcontrollers, the Arduino environment is one big trove of usable and not-so-usable code, and it is written in a subset of C++. In C, when writing modular or library code, there is really only one global namespace, so naming the interface functions and objects is rather critical. Typically that means having a prefix (or suffix) of the library name as part of the name, which is a bit annoying. In C++, classes provide a nice namespace separation, and makes combining C++ code from different sources easier. The only trick, really, is to find out what thatsubset of C++exactly is. It has no strict boundaries, because different microcontroller environments provide slightly different subsets of C++.So, really, the real-world discussion should not be whether one should switch from C to C++ when working with microcontrollers, but which subset of C++ is appropriate for which tasks, and in which cases e.g. freestanding C is more appropriate instead. Unfortunately, we'd need to talk about that openly all the time, because it depends on so many variables (hah; I mean, compilers and libraries and hardware change constantly, at a rather rapid pace); but all discussions on this I've seen eventually degrade into worthless bickering and bikeshedding.

author: shangaoren
author_rank: Regular Contributor
timestamp: January 14, 2019, 10:20:28 am
content: I'm working on embedded systems, our company is partner with STMicroelectronics, we use a custom RTOS that is designed in C++, i wrote my own open source RTOS in C++.If you take care of what you do, C++ is not more messy than C, it's just the language that give you more possibilities, so more possibilities to do crap.I will never go back on my own to C because of templates, references instead of pointers, overloading, and object oriented by examples, the code is more easy to read, references can avoid many errors.With modern tools C++ isn't that hard to debug if you know what you do.A well written C++ code can be more efficient than C or assembler one, we have a fully autonomous drone than run with a cortex M4 spending 70% of his time in idle state.If you need to know what's going on under the hood have a look at this :https://godbolt.org/If you want to try C++ in embedded, go for it, as long as you know what you are doing everything would be fine, you will be able to do all the things you wants in Assembler/C or C++ but for me C++ is much more handful.When you want to go somewhere, you can walk, go with a bike, or with a car, the result will be the same but you will not need the same amount of time

author: bogdant
author_rank: Regular Contributor
timestamp: January 14, 2019, 11:04:05 am
content: What subset of C++ will be useful for microcontrollers?Comming back to the problem I am facing: I add the .ctor and .dtor in the linker file, but in map file the sections are empty. I am missing something here.Here is the options compiller called.....Building file: ../Drivers/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.cInvoking: MCU GCC CompilerC:\myfiles\radio103\firmware\radio\Debugarm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -mfloat-abi=soft -std=c11 '-D__weak=__attribute__((weak))' '-D__packed=__attribute__((__packed__))' -DUSE_HAL_DRIVER -DSTM32F103xE -I"C:/myfiles/radio103/firmware/radio/Inc" -I"C:/myfiles/radio103/firmware/radio/Drivers/STM32F1xx_HAL_Driver/Inc" -I"C:/myfiles/radio103/firmware/radio/Drivers/STM32F1xx_HAL_Driver/Inc" -I"C:/myfiles/radio103/firmware/radio/Drivers/STM32F1xx_HAL_Driver/Inc/Legacy" -I"C:/myfiles/radio103/firmware/radio/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM3" -I"C:/myfiles/radio103/firmware/radio/Middlewares/ST/STM32_USB_Device_Library/Core/Inc" -I"C:/myfiles/radio103/firmware/radio/Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc" -I"C:/myfiles/radio103/firmware/radio/Drivers/CMSIS/Device/ST/STM32F1xx/Include" -I"C:/myfiles/radio103/firmware/radio/Middlewares/Third_Party/FreeRTOS/Source/include" -I"C:/myfiles/radio103/firmware/radio/Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS" -I"C:/myfiles/radio103/firmware/radio/Drivers/CMSIS/Include" -I"C:/myfiles/radio103/firmware/radio/Middlewares/Third_Party/FatFs/src" -I"C:/myfiles/radio103/firmware/radio/Drivers/lcd" -Og -g3 -Wall -fmessage-length=0 -fno-verbose-asm -ffunction-sections -c -fmessage-length=0 -MMD -MP -MF"Drivers/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.d" -MT"Drivers/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.o" -o "Drivers/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.o" "../Drivers/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c"Finished building: ../Drivers/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c.....arm-none-eabi-g++ -std=c++1y '-D__weak=__attribute__((weak))' -DSTM32F103xE -DUSE_HAL_DRIVER '-D__packed=__attribute__((__packed__))' -I"C:/myfiles/radio103/firmware/radio/Middlewares/ST/STM32_USB_Device_Library/Core/Inc" -I"C:/myfiles/radio103/firmware/radio/Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc" -I"C:/myfiles/radio103/firmware/radio/Drivers/CMSIS/Device/ST/STM32F1xx/Include" -I"C:/myfiles/radio103/firmware/radio/Middlewares/Third_Party/FreeRTOS/Source/include" -I"C:/myfiles/radio103/firmware/radio/Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS" -I"C:/myfiles/radio103/firmware/radio/Drivers/CMSIS/Include" -I"C:/myfiles/radio103/firmware/radio/Middlewares/Third_Party/FatFs/src" -I"C:/myfiles/radio103/firmware/radio/Drivers/lcd" -I"C:/myfiles/radio103/firmware/radio/Inc" -I"C:/myfiles/radio103/firmware/radio/Drivers/STM32F1xx_HAL_Driver/Inc" -I"C:/myfiles/radio103/firmware/radio/Drivers/STM32F1xx_HAL_Driver/Inc" -I"C:/myfiles/radio103/firmware/radio/Drivers/STM32F1xx_HAL_Driver/Inc/Legacy" -I"C:/myfiles/radio103/firmware/radio/Drivers/CMSIS/Device/ST/STM32F1xx/Include" -Os -g3 -Wall -c -fmessage-length=0 -fno-verbose-asm -MMD -MP -MF"Src/Radio.d" -MT"Src/Radio.d" -o "Src/Radio.o" "../Src/Radio.cpp"Finished building: ../Src/Radio.cppInvoking: MCU G++ Linkerarm-none-eabi-g++ -mcpu=cortex-m3 -mthumb -mfloat-abi=soft -specs=nosys.specs -specs=nano.specs -T"../STM32F103RETx_FLASH.ld" -Wl,-Map=output.map -Wl,--gc-sections -fno-exceptions -fno-rtti -o "radio.elf" @"objects.list" -lmThe build is finished with success.I use gcc in System Workbench STM32 / WinIdea Open/J-link/Custom board with stm32f103.

author: legacy
author_rank: Super Contributor
timestamp: January 14, 2019, 11:05:32 am
content: I am writing, just right now, polymorphism in C##It#can##bedone(funny, or odd?, that is the problem)

author: legacy
author_rank: Super Contributor
timestamp: January 14, 2019, 11:07:06 am
content: Quote from: shangaoren on January 14, 2019, 10:20:28 am

author: shangaoren
author_rank: Regular Contributor
timestamp: January 14, 2019, 11:26:23 am
content: Quote from: legacy on January 14, 2019, 11:07:06 amJust as every languages no news here, the crap came from the man who do the code, not the language ...Quote from: legacy on January 14, 2019, 11:05:32 amyou can cut a tree with a knife too, but why would you do that ?

author: shangaoren
author_rank: Regular Contributor
timestamp: January 14, 2019, 11:37:18 am
content: Quote from: bogdant on January 14, 2019, 11:04:05 amI don't understand your problem, you don't need to modify the linker script, in the startup there is a function with a name like "__libc_c_init_array" or something like this, this function is here to call your ctor. you don't need to have dtor unless you use dynamics instantiation which is not a good idea in an embedded system

author: Nominal Animal
author_rank: Super Contributor
timestamp: January 14, 2019, 11:46:26 am
content: Quote from: shangaoren on January 14, 2019, 10:20:28 amYou do realize that claim is completely preposterous, or a straight lie? That is exactly the kind of argument that has negative value in a serious discussion.Nothingcan be more efficient than assembly code, because is is just an exact representation of the machine code compilers generate. Sure, you're going to weasel out of that by claiming that you meant something else, like if you compare the C++ code to the C or assembly code you or your colleagues write, but that's like me saying that English is a poor language because I can express myself in Finnish more clearly and with more finesse. It is an idiotic argument, and exactly the kind of shit that drives me crazy.That kind of crap might fly here, but it really is like claiming that those $5000 digital audio cables do sound better, because the ones and zeros have better fidelity on those cables.(No need to say anything, Simon; I'll shut up. I tried to avoid this thread, but failed.)

author: Berni
author_rank: Super Contributor
timestamp: January 14, 2019, 12:08:22 pm
content: That depends on who is writing assembler. Of course C++ can't be faster than the optimal assembler code. But do mortal programmers write optimal assembly code every time?I think C++ with the right optimization flags tends to generate more efficient code than what you would get if you have someone write it directly in assembler. Over time C compilers have become pretty smart at optimizing code on the widely used architectures, so the machine code that pops out is pretty close to optimal (Given optimal C code was fed to it). A human writing assembly code is likely to miss some optimization opportunities or skip over ones that are particularly annoying. A experienced assembly programmer that has great understanding of the architecture can write really optimized short snippets of code, but once the piece of code becomes larger and more complex it gets a lot more difficult for a human to keep pace with a C compiler.The general idea is that optimal C code is easier to write for a human compared to optimal assembler code. But C can usualy convert optimal C code into near optimal machine code while large blocks of hand written assembler are a lot of work to write and harder to maintain later on.So for most real world cases C++ is indeed faster than assembler once you consider realistic human factors. These human factors are only exaggerated even more once the typical tight deadlines start to rain down from upper management on the said human.

author: Otatiaro
author_rank: Regular Contributor
timestamp: January 14, 2019, 12:12:31 pm
content: Hello,I will focus only on embedded C++ (mainly on STM32 for my experience), for PC development I use mainly C#.NET.From my point of view there is 3 categories of persons about this subject:1 - people who will not use C++, ever, because they love C, they love the way they work (forgive me but I depict them as using VI for code editing, launching compiler with command line and debugging with LEDs/UART ... a bit caricatural I know, but sometime not so far from reality). I won't try to convince them to switch to C++, not even to try it out, because they are convinced C++ is bloaty, that OOP leads only to bad code, and technical reasons so out of date or utterly wrong (no an object does not have pointers on all it's members functions ... it MAY have a vtable for certain virtual methods, depending on the compilation options and many other parameters) that it's not even a debate, it's talking to walls.2 - people who already use C++ when they can. They already know why they use it, so I guess we can share ideas, tips and tricks, but I don't have to convince them anymore.3 - people that use C because "isn't it what people use for embedded ?", who already use "modern" tools (IDE based Eclipse or visual studio, a real debugger with fancy options like stepping, breakpoints, memory analyzers, etc.), and who wander why would they use C++ in addition to C. Those are my target today, if I do my job correctly they will try it, maybe not like it and revert to C, but I'm pretty sure some of them will discover a new world of possibilities.That being said, why and more importantly HOW would you use C++ for embedded development ?First you have to understand language is only a tool. You can do wonders with inadequate tools if you are very experienced, but a good tool makes the job easier.Reminds me a cartoon I used to read when I was young "Leonard : genius", where he sees woodcutters using a manual saw to cut a tree, he first give them a chainsaw but forgot the gas to put in, so he go get some gas and when he come back the woodcutters are using the chainsaw as a manual saw, complaining it is heavier and does not cut as well as their manual saw ...That's the main point for C++, it's a very efficient tool if you learn how to use it, and use it right :- C++ is not OOP C- embeddded C++ is not desktop C++- I'd say there is not one C++, there are as many C++ as developers or teams of developers using itWhat we don't use in embedded C++:- exceptions : an embedded program is often structured as "init then while true do always the same thing again and again", you should handle error cases, not rely on exceptions that are useful only on high end OS like windows or linux.- reflexion : same reason, in embedded you don't load code dynamically, everything is known at compile time, so there is no use for reflexion (RTTI or Real Time Type Information)- dynamic allocation : again, almost everything is known at compile time, and memory is very limited compared to a PC, so almost everything should be statically allocated, and data with unknown (but bounded) size be allocated in specific, dedicated buffersMost of the embedded C++ tools I know of disable exceptions and RTTI by default, so you don't have to care about it. Dynamic allocation is permitted by default, our framework overrides the default "new" with an error, so that you know you should not use the default new (you can still override it for specific purpose).Encapsulation is the ability to specify what part of your object is accessible from the outside. If you look at a C struct, what field can I change directly, what should be changed by using a function (and where is this function's code anyway ...) ? In C++ you describe your object, it's inner working, and the interface, i.e. how should people or other objects interact with your object. When you work as a team, and you need to code some classes for someone else, you first define the interface, it makes things so much easier, and then you can change the inner working of your class, he can change how he uses your class, without any breaking change. C has everything accessible, so either you are working alone and know what to do and not to do, or you will need to write extensive documentation about how to use your struct, when you can change the fields directly or need to go through accessors, etc.Because of the dynamic allocation, you also will not use many of the provided STL data structures because they are targeted at PC development and heavily rely on dynamic allocation (yep, no vector allowed here ...).But the good thing is you will write your own data containers, once. Want to use linked lists ? Write a template, debug it and you're done, no need to write it again.Templates gives the ability to describe features or concepts, that do not depend on the underlying type: how a list works does not depend on the list item type ... an integer list works the same way as a float list, or a list of objects.Code once, debug once, use it for free for the rest of your life.Virtual methods are cheap performance wise.Worst case it is an additional dereference (through the vtable), but in many case the compiler will know at compile time what is to be called and will optimize it for you. What are virtual methods ? A way to link an object to a specific member function (in case two objects should call different code for the same method), of course you can do it in C (there is nothing, output wise, that can be done in C++ that cannot be done in C), but then you will have to handle the vtable yourself, update it, make use of it manually, etc. C++ compilers does the same, except with a simple keyword you can tell it to do the work for you. You may not understand why it is so useful right now, but there is a point where you face a problem, and having a pointer to the code in the object itself is the solution ... C++ already have the tools available for you.C++ is a modern programming language. There is C++17 (2017) currently implemented in most compilers, and C++20 (2020) will probably have concepts, which will be awesome. C++ improves on new features, sure, but also a lot on making it easier and simpler. C ... well, last C standard is C99 ... yes, 1999.In many case, simple C++ is simpler and faster than C.Ok let's take a very simple exemple, I want to create a buffer of 30 bytes and fill it with a specific value (say 0x55), let's see how to do it in "simple C" (some would say simplistic C), in "simple C++", then in "advanced C" and "advanced C++":Simple C:uint8_t buffer;uint8_t i;for(i = 0; i<30; i++)buffer= 0x55;Simple C++:std::array<uint8_t, 30> buffer;buffer.fill(0x55);Let's compare them:- lines of code : 4 lines vs 2 lines. Well yeah you could- readability : yeah a simple for loop is not that hard to understand quickly for an experienced developer ... but agree that buffer.fill is more expressive, no ? You don't have to understand what it does looking at the code, it's self-describing ...- performance : I tested it on Atollic, running it on the actual STM32, the C++ version is MUCH FASTER than the C version. Why ? Because by default array.fill can optimize much more than the for loop (STM32 is a 32 bit platform, so fill will transfer 32 bit at a time instead of 8, and also move multiple 32 bit registers at a time to maximize throughput).- bug-prone : how many times does C++ repeat the buffer size ? None. Whereas the C code duplicates the "30" magic number, so there is a chance you change the buffer size later and forget to change the for loop condition, ending in memory corruption. Ho and by the way, what happens in C code if I change the buffer size to 300 ?- memory : it is the EXACT SAME result on both, they use only the required memory space, that is 30 bytes. But then you will ask, how the hell does fill knows the buffer length ? It is a sort of "compiler only" variable, that the compiler know, but that will not take space in memory if not needed.Now I hear some C dev shouting at me, saying that is not good C and nobody writes such code. From my experience, the vast majority of C developers write this type of code.But let's see the "advanced" version, something a more experienced C or C++ developer would probably write:Advanced C:uint8_t buffer;memset(buffer, 0x55, 30);Advanced C++:std::array<uint8_t, 30> buffer;buffer.fill(0x55);Let's compare them:- Yes, read it again ... the "advanced C++" is the exact same as "simple C++", I even copy-pasted it to make sure it was exactly the same.- C is now 2 lines of code, same as C++- readability : well, memset of not that bad, let's say it's a tie even if I think fill is more meaningful.- performance : I'll be honest, from my tests C was just a bit faster (a few percent at the very best) depending on the compiler options. So that's a point for C, that I would mitigate because on the simple case C was many times slower than C++ (not a few percent), and just because you still can write the C version in C++ and get the same performance in case you really need the extra clock cycles (but then I'm pretty sure you can optimize a lot more somewhere else in your code...)- bug-prone : C still repeats the buffer size, but at least memset uses a 32 bit index by default- memory : same as beforeWhat I want to show you is C++ is easier to write "good / not so bad" where beginner C developers often use bad behaviors. Why ? In C you have to search for the memset function, understand how it works, if you don't know it exists then you will use the for loop. In C++ if you have the right tool, you just type ctrl-space and you are presented with the possibilities ... there is a fill function on a buffer ? does it do what I expect (you still need to write documentation, but far less) ? yes ? then just use it and get 98% of the performance I'd get using advanced C (and many times faster than simplistic C).Also not repeating the buffer size is one of the major, if not the best, feature of C++. Contrary that what some may say, C++ is not bloaty but it has plenty of tools to make lighter code size / memory footprint / code performance.One of them is the constexpr keyword, constexpr tells the compiler it may have everything at hand to compute the result of some arbitrary code, and then it should do so (compute the result at compile-time, not at runtime).Compilers do that kind of optimization for years, even in C, but you have absolutely no way to tell the compiler you want it to be that way. With constexpr you can both ask the compiler to compute at compile-time, and ask it to enforce that it can compute it at compile time (so that you cannot modify the code in a way it's not anymore and you loose runtime performance without knowing why). What if you don't use constexpr in C++ ? Well you get the same behavior as C, if the compiler can optimize, it will ... maybe, maybe not.And constexpr variables do not use memory in the final binary code !!!! You can define HUGE constexpr variables in embedded code, it will not use any of your few kB of RAM, it will only use a small portion of your multi GB PC RAM.So what you will be using extensively when switching from C to C++ in embedded projects:- constexpr to make as much as possible your PC do calculation instead of your small microcontroller.- templates to reuse data structures as much as possible, writing less code (and less code means less bugs)- public / private to show only what you want of your object- at some point you will probably face problems that have good solutions built in C++ (virtual methods, std::function, lambdas, etc.) At least as good as what you would do as an experienced C developer, except the compiler does part of the job for you, if you drive it correctly.Here in my team we develop for embedded in C++ for a few years. We developed our own in-house RTOS for Cortex-M(3/4/7), our own framework of data structures, drivers and devices that we can reuse on all projects.We have been invited in the ST partner program last year and we are in tight discussion with ST about this subject, we plan to make seminars/webinars on this subject too (at first in French, sorry), and they are still amazed at the performance we get out of their controllers, even compared to very experienced C programmers/teams.And ask my team members about it (@shangaoren is one of them), they really embraced the C++ way of thinking and clearly see why we use it.If I managed to get you interesed in the subject (YES !), then here is a few resources that you may find vey helpful:-https://godbolt.org/compiler explorer, this tool is so nice to understand what the compiler does under the hood, and it includes ARM Cortex-M compilers. So helpful to understand the effects of optimization flags, etc.-about constexpr, and especially this oneshows C++ is also targeted at very small platforms with efficiency in mind.- The cppcon talks :https://www.youtube.com/results?search_query=cppconsome of them are mainly/only targetted at PC development, but a vast majority are applicable to embedded development.- Jason turner youtube channel :https://www.youtube.com/channel/UCxHAlbZQNFU2LgEtiqd2Mawwith C++ weekly, these are short technical videos on specific C++ aspects.Let me know if you need more, or want to discuss specific aspects/features of C++ for embedded.Thomas.

author: Otatiaro
author_rank: Regular Contributor
timestamp: January 14, 2019, 12:32:23 pm
content: Hello,Quote from: Nominal Animal on January 14, 2019, 11:46:26 amI think you are overreacting because you know a bit better formulated he is perfectly right, let me improve just a bit the writting of what he meant:"A medium written C++ code can be more efficient than medium written C or assembler one".And that is exactly what I desmonstrated just above using the buffer fill problem, and it's perfectly true.I'd even say that medium written C++ will most probably be faster that medium written C, and definitely be faster than medium written ASM. Plus it is easier to read, far less error-prone, far easier to write, re-usable (compared to ASM), and much more.So yay on the performance aspect, for a specific task, that really need ultimate optimization, MAYBE C or assembler can be a bit faster than well written C++.What percentage of developers are able to write correct, fully optimized ASM ?How many of these happy few can optimize the program outside the boundary of one or a few functions (optimizing code over the entire program, depending on how it's called and the context) ?And then, what time will it take for them to write this ASM code, compared to C++ ?What happens if somebody else need to read and understand this code ?Our in-house RTOS uses some ASM code, not for performance but to access platform specific resources that are not available in plain C++ (SVC and context change mainly). So ASM has it's usage, I'd just not place performance on top of my list.Thomas.

author: Otatiaro
author_rank: Regular Contributor
timestamp: January 14, 2019, 12:39:56 pm
content: Quote from: Nominal Animal on January 14, 2019, 11:46:26 amAnd I prove you wrong :int main(){int a = 1,b = 1;return a+b;}Versus (probably not 100% correct, I'm writting it on the fly):movs R0, #1movs R1, #1adds R0, R0, R1BX LRWhy ? Check on godbolt.org, the C++ code (which is perfectly fine in C, by the way) outputs "movs r0, #2 | bx lr".No optimized ASM code can do better (that I know of at least ...).And I'm begin gentle with you, if you want to play with words I could have added a couple NOP in the ASM versionThomas. I was about to tell you to actually watch the youtube video of Jason Turner about the commodore 64 experiments, but you clearly are to be classified in the first category I described. Nothing we can write, explain, prove to you will make you change your mind.

author: NorthGuy
author_rank: Super Contributor
timestamp: January 14, 2019, 03:25:21 pm
content: Quote from: bogdant on January 14, 2019, 06:29:02 amOOP is a programming concept. This is not equivalent to C++. You can do OOP in C as well, or in assembler if you wish.The idea is very simple. An object contains data combined with functions. These functions are called methods. The user of the object doesn't know what's inside the object - the only thing exposed is how to find and call virtual methods. Thus, you can write a program which uses the object without knowing how the object works. This is a general idea.Implementations may be vastly different. C++ is one. Objective-C is another. These two have very little in common. You can create your own if you wish to, according to your needs. Linux kernel uses OOP ideas in C.Whether you need OOP or not depends on your design. There are cases where OOP can help a lot. You may even find that you're already using OOP ideas even though you don't call it OOP. There are cases where OOP can produce tremendous bloat.

author: rhb
author_rank: Super Contributor
timestamp: January 14, 2019, 04:22:19 pm
content: Quote from: Nominal Animal on January 14, 2019, 11:46:26 amIf you read some books on modern compilers and computer architectures, e.g. Muchnick and Patterson and Hennessy you'll learn how and why good compilers can generate much better assembly code than humans.It's rather like a computer chess program. The computer can look far deeper into the future execution path than a human. A 1 cycle reduction now may mean a 10 cycle penalty 1000 instructions from now.But claiming that C++ compilers can generate better code than C compilers is silly. Dereferencing a method pointer at run time costs cycles. And those method pointers take up space. By design C++ takes more space and cycles for the same result.If you use tight encapsulation in C you can get the same result, but the addresses will be bound at compile time. No pointer dereferences or method tables required. You'll get the benefit of the deep look ahead and the actual result at run time will be far more predictable.@NorthGuy is quite correct about OOP. OOP trades space and execution time for programmer convenience. Sometimes this is useful. But I think the main contribution OOP has made is that it lets people pretend that they know how to program.

author: mark03
author_rank: Frequent Contributor
timestamp: January 14, 2019, 04:37:10 pm
content: With apologies to the graybeards on here, the first several posts in the thread have it right. If a decent C++ compiler is available for your architecture, you should seriously consider using it. Used properly, embedded C++ imposes no size nor speed penalty, while providing better code organization and readability. Anyone telling you otherwise is speaking from ignorance or outdated "experience," incorrectly generalized.Some wacky features of modern C++ like constexpr metaprogramming have the potential to make embedded C++ *more* efficient than C: see for example the Kvasir project (https://github.com/kvasir-io/Kvasir). Setting that aside, let's settle for being merely as efficient as C. Write your code exactly as you did before in C, but take advantage of classes and namespaces to better encapsulate your modules. Don't use the STL. Don't use inheritance at all, or if you must, only simple inheritance. Presto: better code. Are the method calls longer in this case than the same function calls would be in C? Well, everything is known at compile time so in theory the compiler should be able to do an equivalent job. If there is a difference it would be on the order of a handful of instructions, so if that matters then we should be advocating for stuffing as much code into a single C function as possible, to avoid the overhead of function calls to begin with...The only valid argument I ever heard against C++ in embedded design came from one of our clients who said, "you may know how to use C++ wisely, but after the code is turned over to my team, they will do stupid things which they couldn't do in C, so I insist that you write the code in C." He had a point.

author: Omicron
author_rank: Regular Contributor
timestamp: January 14, 2019, 05:29:15 pm
content: Quote from: mark03 on January 14, 2019, 04:37:10 pmAnd that is exactly the reason I don't use C++ anymore. I started as a software engineer in 1992. I've used C++ for a very long time and I used to be a strong advocate for it. The arguments pro are correct. C++ offers a lot of nice features and you can write very clean code in it. The problem with C++ is that C++ is complex. Very complex! In fact it is so complex that every C++ programmer I've ever met, including myself, only uses a subset of the language. Unfortunately this subset is different for everyone. And that is the problem! It's not at all uncommon for someone to have years and years of C++ experience to not even be able to read C++ constructs written by another programmer. Why? Not because the code was bad or intentionally obscure. No, simply because of cultural and style differences that cause both programmers to be proficient in different subsets of the language. Some programmers revel in the advanced meta/template programming features while others never go beyond the particular features used by whatever framework or company guidelines they are working with. If you think you master C++ you are most certainly wrong! And with every new release of C++ the problem becomes worse. This is where C shines. It is simple! And for me that simplicity trumps all the advantages C++ has to offer. It is (if memory serves me) also the reason Linus religiously sticks to C for Linux. He was absolutely right to do so. C++ tries to be too many things to too many people.

author: IDEngineer
author_rank: Super Contributor
timestamp: January 14, 2019, 05:42:02 pm
content: Quote from: Omicron on January 14, 2019, 05:29:15 pmBingo.As I said earlier: C was intended to be a portable Assembly language. If you want a "high level" language, there are plenty to choose from that were written that way from Day One and their underlying architecture reflects this. They're not doomed to seek backwards compatibility with a language written for a completely different purpose.The ideas behind C++ (and Java, and...) have their place. But that place is NOT by adding layers of complexity while weaving in backwards compatibility to an existing language that had totally different goals. The results of such forced marriages are nearly always exactly what Omicron just stated.Quote from: Omicron on January 14, 2019, 05:29:15 pmHow ironic that all of this effort has been expended to make code easier to write and (especially) easier to support, yet the actual result is the exact opposite. Ironic, but not unpredictable!

author: IDEngineer
author_rank: Super Contributor
timestamp: January 14, 2019, 06:16:34 pm
content: Quote from: Mattjd on January 14, 2019, 01:29:59 amIsn't DOD code supposed to be in Ada?

author: legacy
author_rank: Super Contributor
timestamp: January 14, 2019, 06:55:19 pm
content: LOL, here I am: I do Ada for avionics! but upstairs, there are guys of space and defense, and they use C++One of them told me that he still uses DSP56000 assembly for a weird radar engineAnd I am 99% sure that the weather station in the CEO office is programmed in TiniJavaand in Automotive, F1, a guy in the MM team told me that they sometimes useOCamfor their internal stuff.So ...

author: IDEngineer
author_rank: Super Contributor
timestamp: January 14, 2019, 07:12:27 pm
content: Quote from: legacy on January 14, 2019, 06:55:19 pmThe nice thing about standards is that there are so many to choose from.Want to give HR fits? Tell them to find a software guy equipped to support all of those projects. Some Modula experience would be helpful too, just in case!

author: bson
author_rank: Unknown
timestamp: January 15, 2019, 12:53:44 am
content: Quote from: andyturk on January 14, 2019, 04:06:14 amIt doesn't. The linker doesn't generate code, but the default startup may contain a call to libc. If you replace libc however you will need to provide your own, and you also need to add a call to it when you replace the startup code with your own - or your data segment will be uninitialized. Trust me. I learned this the hard way when suddenly everything broke when I upgraded the toolchain...

author: Berni
author_rank: Super Contributor
timestamp: January 15, 2019, 06:30:16 am
content: Yeah things like startup scripts is something you don't have to worry about when compiling C for a OS, because the linker just plops in the standard one by default.But when you get to compiling C to run on bare metal in embedded devices these scripts are pretty much always provided by the user. They need certain tweaks for specific CPUs and might do things that a OS otherwise does like setting up execution privileges or initializing external RAM so that initialized data can be put there. There are also typically blocks of assembler code somewhere that handle the interrupt and exception vectors. These things can be a major pain to debug if they break for some reason.

author: shangaoren
author_rank: Regular Contributor
timestamp: January 15, 2019, 09:14:12 am
content: Quote from: bson on January 15, 2019, 12:53:44 amSorry, wrong word, you're right.Quote from: Berni on January 15, 2019, 06:30:16 ami'm using visual GDB for personal embedded project, the startup file is written in C, it's nicer when a bug shows up

author: Berni
author_rank: Super Contributor
timestamp: January 15, 2019, 10:17:10 am
content: Quote from: shangaoren on January 15, 2019, 09:14:12 amYeah i wish more vendors would do that.Most give it to you in the form of assembler and i sure as heck can't be bothered to translate it to C.

author: newbrain
author_rank: Super Contributor
timestamp: January 15, 2019, 12:29:58 pm
content: Quote from: legacy on January 14, 2019, 06:55:19 pmOut of curiosity: would that beoccamorOCaml?While I know nothing about the latter, an MS-DOS compiler with some support for NETBIOS networking for the former was my master thesis in 1990...

author: legacy
author_rank: Super Contributor
timestamp: January 15, 2019, 01:11:10 pm
content: Code:2016-12-20--01-48-14---2016-12-20--06-22-46 - dev-lang/ocaml - success - user-990-12-412I do sometimes updates to their Linux and UNIX systems. This is what they asked.

author: andyturk
author_rank: Frequent Contributor
timestamp: January 15, 2019, 07:48:21 pm
content: Quote from: NorthGuy on January 14, 2019, 03:25:21 pmGot an example?

author: exe
author_rank: Unknown
timestamp: January 15, 2019, 08:15:45 pm
content: I tried C++ for an event-driven project (UI) and I'm never going back to C again. With a lot of efforts same things can be done in C, but that would just an attempt to do what C++ can do out of the box.As usual, a good C code is better than bad C++ code.PS I allocate memory statically whenever possible.

author: mfro
author_rank: Regular Contributor
timestamp: January 15, 2019, 08:30:25 pm
content: There's a lot more ways to do something in C++ than in C (a very good thing in a team where everybody knows and likes what he's doing).Just because of this, there is also a lot more you can do the nonsense way.Unfortunately, at least as it appears to me, a lot more people/teams do the latter...

author: NorthGuy
author_rank: Super Contributor
timestamp: January 15, 2019, 09:00:36 pm
content: Quote from: andyturk on January 15, 2019, 07:48:21 pmI can explain the mechanism. Say, vendor A builds an object framework consisting of enormous number of different objects. He then does something which links the objects together. For example, he provides save/restore capability, where you can save an arbitrary object to a stream and then restore it from there. Since the compiler doesn't know what objects may be contained in the stream being restored, it just has to include the code which can instantiate any of the objects, including VMTs with all the member functions linked in. Vendor B builds an equally magnificent framework. Then the unsuspecting programmer uses couple objects from the framework produced by vendor A, few objects from the framework designed by vendor B, etc. and creates his own framework. And so on until it gets to the end user which does something extremely simple, but gets lots of unused objects from all these frameworks. Sort of junk DNA if you wish - you have to carry it through generations even though it is never used.Real world example? I was doing some Windows development a long time ago. Microsoft, using C++, had extremely bloated, but yet useless, MFC framework. At the same time Borland, using Pascal, had equally bloated and equally useless VCL object library. I try to avoid such things since then and I think my strategy served me well. I do use OOP for my own things when I see fit.

author: rhb
author_rank: Super Contributor
timestamp: January 16, 2019, 12:28:58 am
content: I'll give an example, xclock(1). In the format I've always used it gives the day of the week, month, day, hour and minute. In X11R4 under SunOS 4.1.x it consumed something on the order of 80 KB. The identical function under OpenIndiana Hipster with Mate consumes 80 MB!I had to replace an Atom based machine with 2 GB of memory that I used exclusively for internet access with a Z400 with 8 GB of DRAM just to run Firefox when I updated to Hipster. Firefox consumes so much memory and has so many memory leaks it's ridiculous. Before I replaced the Atom based system I had to kill and restart Firefox every day because of the memory leaks. Interestingly certain web sites caused most of it.As NorthGuy pointed out, lots of frameworks are not well organized. So including a single facility will bring with it a huge amount of code. Use a few frameworks and you're talking a lot of memory.John Lakos wrote a very good book on the issues. But sadly no one seems to have bothered to read and apply what he wrote.I'm one of those greybeards that people don't confront more than once. I could quote chapter and verse from the transistor and the wire all the way up to the OS and UI layer until everyone's eyes glazed over. After 10 years of retirement, much of that has been displaced by other things. So I get very frustrated doing tasks I used to know forward and backwards. But put me back in a working environment and in 6-9 months I'll be as good as ever. I've still got 80 ft of computer books and can read *way* faster than most people.As far as I'm concerned, if you don't know the standard for the language you're using and *check* it when you do something unusual, know the linker and library behavior in intimate detail, you're not a programmer. You're an imposter. Interestingly a recent survey found that over 50% of software developers felt they were frauds. I was quite astonished that so many had that level of self perception. At least for them there is hope. There is none for the other 40%.If someone puts 100 functions in a file, compiles it and puts it in a library, if you call 1 function out of the 100, the system will allocate memory for all 100. Because resolving the dependencies is NP-hard, the problem can only be solved by tight encapsulation and limiting files to only those functions which *must* be in the same file.

author: IDEngineer
author_rank: Super Contributor
timestamp: January 16, 2019, 03:19:30 am
content: Quote from: NorthGuy on January 15, 2019, 09:00:36 pmOMG, I had finally erased MFC from my memory and then I read this. It'll take a month of therapy to scrape out those experiences again.Speaking of Windows: When I was doing OS-level and driver development for Windows, I noticed that Microsoft did NOT use C++ in those areas. C++ within MFC? Sure, why not, that's for merecustomersto use! But in the actual operating system and the driver framework for it? No C++ to be found. Remember the old "eat your own dogfood" mantra? Well, Microsoft wasn't eating C++ in their critical products. Maybe the Office suite was written in MFC, I wouldn't know about their applications business.As always, YMMV.

author: Berni
author_rank: Super Contributor
timestamp: January 16, 2019, 06:13:04 am
content: Oh Microsoft Office, that sure is a good example of legacy crap dragging on.As a result on a modern 64bit machine with modern office i had a problem piloting a chart of voltage versus time if the time span was too long. I think something weird happened when time reached 32 768 (surprise surprise signed 16bit int). I think i eventually gave up on the built in time formats and just used hours as a normal float number on the X axis on my graph.This is just one example of what some old legacy piece of code being dragged on for all these years did.

author: bogdant
author_rank: Regular Contributor
timestamp: January 16, 2019, 08:57:38 am
content: The video is brilliant, me and my colleagues had a good laugh

author: exe
author_rank: Unknown
timestamp: January 16, 2019, 10:38:04 am
content: Quote from: rhb on January 16, 2019, 12:28:58 amI'm not sure what the conclusion here as afaik mate is written in C. So, it's not just about language. Bloatware can be written in any language.Quote from: rhb on January 16, 2019, 12:28:58 amAfaik clang/gcc can do "link time optimization" and will strip unused functions. It's called "dead code elimination" or something.I think, guys, there is a lot of bias in the thread. While I don't like many programs/firmwares written in C++, it's not about language itself. It's just people abuse the technology. Many libraries are horribly huge, but they don't need to. I myself found a middle ground -- chibios + async io + own simple classes for abstraction. I believe code size and memory usage is okay as I'm trying to track resource usage.

author: cv007
author_rank: Frequent Contributor
timestamp: January 16, 2019, 01:08:18 pm
content: It makes little sense to compare the pc world with the microcontroller world. I find it difficult to find my way around the Linux kernel- therefore I should not use C? Micropython seems to be doing C++ in C and I can't read that either, therefore I should not be using C or anything that resembles C++? Firefox is bloated, therefore I should not use C++ on a SAM10D? Microsoft produces some crappy tool (or tools), so I should stay away from C++? There should be no requirement that I have to be able to read everyone else's code, or be able to produce the same thing, before I can use a particular language.here is a simple example of c++ in a small micro-https://github.com/cv007/Samd10XplainedMini/blob/master/main2.cppnothing special, its just me, a compiler, a datasheet, a startup file, a linker script, and everything but the startup file in c++I'm not familiar with a sam10d, just checking it out, I have no debugger either but only ended up with an exception once (alignment error, which I knew was probably coming so didn't have to struggle with it)this simple example compiles to about 2.5k, so is not a bloated messthe simple delay class means I can create as many delays as I want, wherever I want, blocking or non-blockingthe morse class means I can push out any number of messages on any pin, all at different rates if wantedand everything becomes simple, easy to organize, easy to reason about, and ultimately more reliableI don't know what this simple example would end up looking like in C, but I'm quite sure I would take the C++ version any day of the week

author: legacy
author_rank: Super Contributor
timestamp: January 16, 2019, 02:21:17 pm
content: Quote from: cv007 on January 16, 2019, 01:08:18 pmbah. Sony's tools for the Playstation are made by Microsoft. They are not so crappy as one can imagine but rather brilliant. I don't like Microsoft for products like Windows, but I appreciate Microsoft for products like WindowsCE, which comes from the acquisition of the project "Pulsar". Not made by Microsoft, simply bought and rebranded.Anyway, there is a very big difference between the C++ used in "Pulsar", and the C++ used in the Windows (even in theNeanderthal Technology, aka NT).What makes me perplex is that the whole computer science is not producing anything as better as what we had in the 90s.

author: NorthGuy
author_rank: Super Contributor
timestamp: January 16, 2019, 02:35:44 pm
content: Quote from: cv007 on January 16, 2019, 01:08:18 pmBeauty is in the eyes of the beholder. It's the result that matters, not the language. You could've done exactly the same with C, or assembler, for that matter. If you want to use C++, it would be silly to tell you that you should use something else. It doesn't really matter what other people use and what they write.When you look at a painting, do you really care what kind of brush the painter used to paint it? How silly would that be to tell Raphael that if he used different brushes his paintings would be better? Would his paintings be as good as they are if, instead of following his own path, he would worry about what other painters do?

author: Yansi
author_rank: Super Contributor
timestamp: January 16, 2019, 02:55:11 pm
content: It's fun watching comparisons of programming dick lengths, but what matters, is what the safety standards tell you to use and how to write fail safe code.One thing is to sour sketchy sketches to arduino in C++, while writing code for a product, that will actually be sold and certified is a completely another.C++ is not the industry standard for safety concerned applications as far as my knowledge goes, as it is hard to statically analyze for errors.Hence why I stick with C and don't care about C++.cv007has also posted a nice example of unreadable code. Who can tell what it's doing? I can't. But I very likely would, if it would be written in anything else, but a C++.I work now for almost 5 years in a place, where we review many and many customer application HW and application code. Very very rarely there is something written in a C++.

author: exe
author_rank: Unknown
timestamp: January 16, 2019, 03:49:32 pm
content: Quote from: Yansi on January 16, 2019, 02:55:11 pmIf it was C, it would be pretty much the same abstraction, except the need to reinvent the wheel. Anyway, try this one:https://www.ioccc.org/2018/bellard/prog.cQuote from: Yansi on January 16, 2019, 02:55:11 pmIt's a pity security-critical applications are still written in languages with manual memory management. C++ at least gives some "smart" pointers to partially mitigate the issue, while I'm not aware of such methods available for C. So, I question your security standards. They may be "state approved", but doesn't mean there are no better options.

author: cv007
author_rank: Frequent Contributor
timestamp: January 16, 2019, 03:55:49 pm
content: QuoteThe original poster (or Raphael) asked about using a different brush. Since it was asked, I'm just suggesting that brush x is nice to use, but I'm not telling anyone how to paint and ultimately I really don't care what brush anyone else uses. Just trying to point out good features of brush x.I'm not trying to sell something, and I'm not on the 'C++ for a better world committee', just trying to suggest another tool in the toolbox may be beneficial. But probably not doing a very good job of it.QuoteI think that is the linux serial port driver for my onion omega2 board.

author: IDEngineer
author_rank: Super Contributor
timestamp: January 16, 2019, 04:00:16 pm
content: Quote from: NorthGuy on January 16, 2019, 02:35:44 pmInteresting analogy. With all due respect, let's dig a bit deeper.Art is SUBjective. Artists don't get sued if their painting "doesn't work", now or in the future. The consumer either likes it or they don't.But Engineering, including code, is OBjective. It can be measured to "work" or "not work". People can be held liable if their code doesn't work, even if that isn't discovered at time of purchase. So unlike artists, Engineers and their employers (should) have a tremendous vested interest in making sure that their code works - and if it's found to NOT work, that it can be quickly and easily fixed by whomever is available.Now let's consider support. A painting is a solo effort. There isn't a team coming along in a few months or years to "fix" it or add features. The consumer either likes it as-is, or they don't. Today, tomorrow, forever.But Engineering, including (perhaps especially) code, often has people coming along later to "fix" it or add features. When there's a problem, the employer and the customer are *extremely* interested in resolving it as fast and as inexpensively as possible. That means two things: 1) There is great advantage to using tools that decrease the likelihood of bugs in the first place, and 2) there is also great advantage to using tools that make it as easy as possible for utter strangers to later pick up the code, grok it quickly, find, and fix the problem.Do downstream "users" of art care about the brushes or the paint? No. But if art were Engineering, they'd care a lot. Example: I recently read an article about matching interior and exterior house paint colors. Paint stores have spectrometers now, so you'd expect a perfect match every time, right? What could possibly go wrong - we're using SCIENCE! And yet the consumers - DIY'ers and professional painters alike - were reporting frustration in the field. The article revealed that what happens is the paint *base* formula is sometimes changed, with the result that the optical absorption spectrum changes too. And this means that the perceived color changes depending upon the type of light source. You can match an old and new color in any single given light (say, incandescent) but when illuminated in sunlight they'll look different. Fluorescent and LED have their own emission spectrums and yield other, different results. Unless you keep an indefinite supply of the same base, and the same pigments, it's likely impossible to match existing paint... you just can't replicate the recipe.Brushes and paint are the "language" of art, but that language can go extinct as soon as the painting is finished. An artist can literally mix his own paints and build his own brushes, and when he (unilaterally!) declares the project finished he can cavalierly destroy all of his tools without risk. Code doesn't have that freedom. To put it in art terms, your code "painting" has to be objectively without error as judged by people you may never meet personally, and then supported, understood, corrected, and extended by strangers whose background you don't know and can't predict. Those strangers have to be able to understand AND duplicate your paint bases, your pigments, your brushes, and your "style" (architecture) at some indefinite point in the future, probably under intense pressure from their employer and its customers. If art were like Engineering, a painting would have to come with a lifetime supply of base... pigments... maybe even the brushes used. But art has the luxury of being subjective. (Yes, there are art restoration projects, but I daresay those folks would side with the concept of NOT using obtuse and opaque tools! Talk about a nightmare.)OK, I'll stop extending the analogy. In short, art doesn't have to worry about being measured or providing support. Code does. A wise software author plans for this in advance and chooses his tools and architecture to be the easiest to read, understand, debug, and extend. And as a personal request: He also includes at least one line of comment next to every line of code, dagnabit!!!We're not time-traveling mind-readers, lend us a hand, will ya?

author: Nerull
author_rank: Frequent Contributor
timestamp: January 16, 2019, 10:50:38 pm
content: Quote from: Yansi on January 16, 2019, 02:55:11 pmIt's funny, I've seen that exact argument used for why no one should ever program in a memory-unsafe language like C (or C++).Embedded programming has mostly benefited from airgap isolation protecting it from exploitable flaws - you can be certain there is as much hot garbage code written in C in embedded systems as in any other language.

author: Berni
author_rank: Super Contributor
timestamp: January 17, 2019, 06:27:28 am
content: You can write bad code in any language: assembler, C, C++, C# etcIts the job of the programmer to make clear and readable code, the language just provides him with the tools to do that.Assembler is obviously horrible here since it has basically no real structure to it. Then C gives you the fundamental tools for structuring code, but then C++ and C# upgrade on that and give you a huge wide diverse set of tools to structure your code almost anyway you want.So it must be possible to write the cleanest code in C++ or C#. The problem is that most programmers are NOT good at what they do. They learn certain features of a language like C++ and develop them in there specific coding style, sometimes it works, but other times its pushing a square peg in a round hole where language features are misused or abused to get them to do that they want. It only gets worse with teams of programmers. Put 5 of these programmers into a team project and suddenly every part of the project is written in 5 completely different styles. The code ends up separated in these 5 bubbles that each on there own seam reasonable, but then they are reaching into the other bubbles in strange tangled ways that nobody truly understands because that programmer never understood how the other guys 'bubble' really works.With C there is so little features that the programmers tend to learn most of them and so end up using the right feature for the right job rather than forcing in a language feature that they happen to know or like.In the hands of a good programmer C++ is definitely the better tool. It can be just as fast and efficient while structuring code much better. But when you hand C++ to a bad programmer it just makes these code even more of a horror show.

author: Karel
author_rank: Super Contributor
timestamp: January 17, 2019, 07:34:28 am
content: Quote from: Berni on January 17, 2019, 06:27:28 amBut when you hand C to a good programmer it just makes these code more fast and efficient.

author: Berni
author_rank: Super Contributor
timestamp: January 17, 2019, 07:56:40 am
content: You can compile most C code in a C++ compiler just fine and it will run at roughly the same performance.The trick to keeping C speed is to only use features of C++ that can be statically optimized during complication. But good luck explaining that to the typical C++ programmer that has no idea of what is the difference between the stack and heap. C++ is doing all the memory management for them anyway.

author: westfw
author_rank: Super Contributor
timestamp: January 17, 2019, 11:28:22 am
content: QuoteCode structured "any way you want" is almost as bad as code with no real structure at all, what with 50% of programmers having below-median skill.At least with assembler, the chances are pretty slim that a program will be stealthily bloated and slow.QuoteOh yes! We used that argument against going to C++ at some point: "it's too easy to accidentally shoot yourself in the foot."For example, this was recently posted:Code:std::array<uint8_t, 30> buffer;buffer.fill(0x55);That actually looks pretty nice. And I read up on "array" and it doesn't seem bad at all.But if someone were to come along and not pay attention, and use instead ("because it's shorter, and a vector and an array are the same, right?"):Code:std::vector<uint8_t> buffer(30, 55);It might suddenly be very painful, on an embedded system.

author: exe
author_rank: Unknown
timestamp: January 17, 2019, 01:24:29 pm
content: Quote from: westfw on January 17, 2019, 11:28:22 amI believe that meant "structured the we way the project needs".Quote from: westfw on January 17, 2019, 11:28:22 amGood luck with supporting a big assembler project. It's fast in runtime, but very slow in development (and, I guess, expensive).Quote from: westfw on January 17, 2019, 11:28:22 amOh, c'mon, C provides plenty of ways to shoot oneself in the leg.

author: legacy
author_rank: Super Contributor
timestamp: January 17, 2019, 01:39:08 pm
content: Quote from: exe on January 17, 2019, 01:24:29 pmwe need modularity in the first place, meaning that each module needs to define its interface in term of signed/unsigned, range, max use of the stack, behavior in case of problems, e.g. does it trap on overflow?) and error propagation.Quote from: exe on January 17, 2019, 01:24:29 pmAmigaOS-classic and RISCOS {1,2,3} is an example of Kernel and filesystem developed in (macro)-assembly.DrDobbs is another source of examples.The firmware on my Z80-spectrometer was entirely developed in (macro-)assembly, and it contains a lot of complex algorithms.My 68332 spectrometer's firmware was developed in C, and I know that Avocet was used for this.Our AFDX switches were initially developed in C++, but avionics certifications and related stuff have recently pushed guys back to C so our new products are developed with C.The C++ experience failed for us

author: exe
author_rank: Unknown
timestamp: January 17, 2019, 02:04:29 pm
content: Quote from: legacy on January 17, 2019, 01:39:08 pmIt's inverse of "survival bias". There are tons of successful cpp project. Afaik space-x uses cpp.Also, even if a program works well from user perspective, it doesn't mean it's good code. It means it's well tested. I'm pretty sure many "successful C project" are unreadable mess inside.A special case is when it comes to special requirements. I'm fine if cpp is forbidden in military or space environment (but again look at space-x). It doesn't automatically means that it's bad. Even if it fails some requirements, most projects do not expose such requirements. So, should I drop c++ and rewrite my code just because someone works in environment where it is forbidden? Not at all!

author: Otatiaro
author_rank: Regular Contributor
timestamp: January 18, 2019, 01:12:37 pm
content: Hello,Quote from: westfw on January 17, 2019, 11:28:22 amBut is someone were to come along and not pay attention, and use instead ("because it'smore modern, andprogramming languagesare the same, right?") :javascriptItwillsuddenly beextremelypainful, on an embedded system.Programming languages are tools, and the result depend on the way you use it, that's for sure.BUTlike I said, in our framework we override the default "new" with an error basically saying "nope, you most probably are not doing it right". Then if you try to instanciate a vector at runtime with default allocator it would fail and explain you why.Last time I tried to override malloc in C, the compiler didn't understand what I was trying to do ...Thomas.PS : weird for somebody who didn't know about std::array, to compare it with the more advanced std::vector ... this is basically why I prefer to train C++ to a good (open minded !) C programmer rather than a good PC C++ programmer. The C programmer will have to learn new things, the PC C++ programmer thinks he already know how to do it. Except Embedded C++ is different from PC C++.PS 2 : I created a discord channel named EmbeddedC++ to discuss the matter (I mean benefits and how to use C++ for embedded programming, not the C vs C++ debate) :https://discord.gg/DGTr4Cg

author: westfw
author_rank: Super Contributor
timestamp: January 19, 2019, 09:59:55 am
content: Quoteyes, well... I'm very much an ASM or C programmer trying to learn new things. So my C++ exposure comes from Arduino, a couple of online classes (mostly of the "beginning C++" variety, but also one attempt at "C++ for C programmers", which would have been pretty good if the teacher had been better, I guess), and a book or two.Which has meant:STL isn't present (ie Arduino)The STL components that have simpler "pure C" equivalents (like arrays) are not stressed.The "neater" STL components are mentioned. Especially Strings, of course.Whenever I look at actual STL code, I'm immediately presented with horribly unreadable levels of abstraction using language features that haven't been mentioned, and (I guess) standardized "styling" that I haven't seen before. :-(My general impression of the STL is that it's full of exception processing, dynamic allocation, localization, and other stuff that ranges between "not relevant" and "a bad idea" on the class of program I use.I was relatively impressed to find something relatively simple like "array." Although perhaps it's a good thing I didn't look at its source code before saying good things about it :-)Code:voidfill(const value_type& __u){ std::fill_n(begin(), size(), __u); }// Element access._GLIBCXX17_CONSTEXPR referenceoperator[](size_type __n) noexcept{ return _AT_Type::_S_ref(_M_elems, __n); }constexpr const_referenceoperator[](size_type __n) const noexcept{ return _AT_Type::_S_ref(_M_elems, __n); }

author: legacy
author_rank: Super Contributor
timestamp: January 19, 2019, 01:03:11 pm
content: Quote from: exe on January 17, 2019, 02:04:29 pmumm, is C++ suitable for Avionics? Maybe, in theory ...let's check what it meant in my personal experience: we do civil and military flight boards for aircraft(1), and the being suitable for Avionics practically means to be able to satisfy DO-178B Level A-B, whose benefits is that it provides neat criteria for when it is ok to stop testing.It's more complex than this, but basically, the criteria are mainly based on achieving certain code coverage thresholds based on the criticality of the software. The criticality is determined by assessing the worst possible consequences of software malfunction.Guys in the quality assurance office look at the maximal stack usage, which is easy to be tested and verified in our laboratories by specific test-cases and ICEs.This is not easy to be verified with C++ ... and requires more time and effort.Besides, you also have to prove by specific test-cases that your compiler does not generate untraceable code in your specific context.C++ generates a lot of untraceable code, and you have to manually prove that it's correct. "object level coverage" is required, and the traceability study requires more time and effort.Ada is largely better than C++ in this because it providestraceability analysis packages for DO178/*&&COTS traceability studyfor similar purposes, so we prefer Ada for the high level.Code:is_approved=False;while(is_approved isNotEqualTo True){is_ok=False;while(is_ok isNotEqualTo True){development(project);is_ok=testing(project);}is_approved=QA(project);}commit(project);Anyway, combining MISRA+DO178B, C-sources become really neater and easy to be read since one of the goals of the process is involving people with different skills (system designers, developers, testing guys, quality assurance guys) at reading the source: if they don't find it comfortable and understandable the project is not approved.(1) I am involved in the development of AFDX switches, STAP/*, ARINC 424, ARINC 664, etc ... which I autonomously develop and I cannot test by myself (you cannot test what you develop by yourself) but for weird reasons I usually end at testing things developed by my colleagues... and, worse still, I am mainly involved only in the testing team for the flight boards ...... so, in a way, or in the other, I am the one that ends suffering at testing things (d'oh)

author: IDEngineer
author_rank: Super Contributor
timestamp: January 19, 2019, 02:30:37 pm
content: Quote from: legacy on January 19, 2019, 01:03:11 pmThat may be the smartest software evaluation criteria ever. And reinforces my points regarding things like overloading, dynamic polymorphism, etc. Sure, the guy who wrote it in real time might understand what he meant at the time, but do you really want to be the poor sucker whose job it is to figure out what that first guymeantto do, but failed to doproperly? Was it his code? Or did he assume that the equal sign was overloaded to some other functionality in this context, when it wasn't? Or the equal sign really IS overloaded like he thought, but someone downstream forgot to specifythatlibrary so the development environment compiled and linked "successfully" but does something "differently correct" today?QuoteBoy, that's got to be fun with dynamic polymorphism.

author: legacy
author_rank: Super Contributor
timestamp: January 19, 2019, 02:42:28 pm
content: Quote from: IDEngineer on January 19, 2019, 02:30:37 pmwas it sarcasm, ain't it?

author: andyturk
author_rank: Frequent Contributor
timestamp: January 19, 2019, 02:57:18 pm
content: Quote from: westfw on January 19, 2019, 09:59:55 amYeah, no kidding! Much of the C++ standard library is terrifying to look at in source form. But in lots of cases now, the abstractions represented are quite useful for embedded code and not particularlyleaky. I use std::array frequently in code for microcontrollers, but only reach for things like std::vector and std::map in unit tests, where they can be super handy.To me, modern C++ is all about hacking the compiler from within the language itself. It gives a C++ user the ability to do things that only a compiler writer or language implementer can do in other languages. But if you're going to do that well, you need nearly a compiler writer's level of understanding of what C++ is doing. There are two execution envirionments: one on the target, and one inside the compiler itself.For a tiny example, I've been working on a Bluetooth project recently and never liked the static arrays of byte values that people typically use to represent aUUID. I really wanted to be able to use the "human readable" string format for UUIDs in code, but have those magically translate into packed 16-byte arrays. E.g.,Code:const UUID my_bluetooth_service = "268cf9ec-1269-41fb-b6ca-1fd6552468d3";instead of the more typical:Code:const uint8_t my_bluetooth_service = {0xd3, 0x68, 0x24, 0x55,0xd6, 0x1f, 0xca, 0xb6,0xfb, 0x41, 0x69, 0x12,0xec, 0xf9, 0x8c, 0x26,};Turns out it's actually possible to do compile-time parsing of string literals and have a class definition convert the human readable syntax into the same 16 bytes at compile time. That's cool!

author: legacy
author_rank: Super Contributor
timestamp: January 19, 2019, 03:11:28 pm
content: Quote from: andyturk on January 19, 2019, 02:57:18 pmThat's crap. Now, try to imagine that you have to verify this shit with a formal tool (you are not authorized to hack it, neither you have the source) that doesn't understand it. You know how it ends?You have to move your ass to the laboratory, take a goddamn ICE, connect it to the target, load the hex, fill breakpoints here and there, and everything and logging in a file what the compiler has done.

author: hans
author_rank: Super Contributor
timestamp: January 19, 2019, 03:19:21 pm
content: Quote from: legacy on January 19, 2019, 03:11:28 pmHuh what? Don't have access to tools that can disassemble ELF files and read symbols from there?C++ also offers static_assert, which gives a compile-time sanity checker for your code. Trivial checks such as the blow up of struct/class sizes, but also the output of these compile-time manipulations can be put in there.Then you have unit tests for single-stepping through code, static_assert to prevent cross-compilation regressions, and inline assertions for run-time debugging (in unit-tests and potentially on the device) plus providing hints for static checkers (although most formal checking tools need loads more info to work by any stretch of the imagination - and you'd be damned if you useanykind of loop).Programming a device really only should be necessary to check the timing of your program.

author: cv007
author_rank: Frequent Contributor
timestamp: January 19, 2019, 03:26:45 pm
content: Quoteor a morse code table in '.' and '-'https://github.com/cv007/Samd10XplainedMini/blob/090811cc730fe7f14f55f9a0aee69444a7f51264/Morse.cpp#L13not difficult to find the result, either if wanted-Code:arm-none-eabi-objdump -d Blink.elf | sed '/morse_table>:/,/^$/!d'00000d0c <_ZL11morse_table>:d0c: 04080201 0304040a 04020100 04000306 ................d1c: 04070200 04040305 02020203 04060307 ................d2c: 0302040d 01010300 04010301 04090303 ................d3c: 040c040b 050f051f 05030507 05000501 ................d4c: 05180510 051e051c 00000000 ............or to create a wide char for a string descriptor when wide character size needs to be 2 bytes-https://github.com/cv007/PIC32MM_Curiosity_CPP/blob/ef60556c57d663875b1e816b69e780309345d1dd/USB/UsbCdcAcm.cpp#L12(although needed #define macro help also, but there may be a way without)lots of uses, just takes a new way of thinking which can be a little difficult

author: legacy
author_rank: Super Contributor
timestamp: January 19, 2019, 03:34:54 pm
content: Quote from: hans on January 19, 2019, 03:19:21 pmThis is not good to convince QA guys to accept your work. They do not want to disassemble anything (neither they have the skill to do it), they have to look at test-reports, so you have to go to the lab and produce documents that they are willing to consider.

author: andyturk
author_rank: Frequent Contributor
timestamp: January 19, 2019, 03:38:18 pm
content: Quote from: legacy on January 19, 2019, 03:11:28 pmWhoa there cowboy! I'm not writing stuff where people might die. We don't need formal verification. And I'd wager that most of the STM32 projects out there (which is how this thread got started) don't need the kind of process or formal approach that your work requires.My unit tests are much less rigorous than your formal verifications. But so what? That has little to do with the language itself and more to do with the project and its goals.

author: legacy
author_rank: Super Contributor
timestamp: January 19, 2019, 04:49:13 pm
content: yup, I was simply summarizing a part of what got pubblished by CAS-T (Certification Authorities Software) Team:QuoteSo we have collected FAA strongly recommendations {1992, 1998, 2002, 2010, 2014, 2018, ...} using RTCA/DO-178B as the vehicle to demonstrate that software is airworthy, and *if* theverification to DO-178B objectives is a labor-intensive effortsince an engineering team + testing guys will spend between one and four hours verifying each line of code to demonstrate compliance to Level A, *the C++ DO-178B compliance* is more onerousbecause of the potentially complex nature of C++ code.What I want to make it absolutely clear is that *hipster* features such as inheritance, overloading, and polymorphism will complicate traceability and structural coverage, and potentially lead to code that contains latent defects of unexplored behavior!In short, due to the lack of standard guidance and tools rules leads many certification representatives to review an applicant closely who is using C++, which can result in project delays or rework.Talking about my specific experiences with the AFDX switches and alike, I can model the process with the following piece of pseudo-C-code:Code:uint32_t subrelease;uint32_t minrelease;minrelease = 0;subrelease = 0;is_approved=False;while(is_approved isNotEqualTo True){is_ok=False;while(is_ok isNotEqualTo True){development(project);/** draf version* tools are employed* to assist in satisfying* DO-178B objectives*/is_ok=testing(project);subrelease++;}is_approved=QA(project);minrelease++;}commit(project);Let's consider variables before is_approved becomes equal To Truewith C approach, minrelease=5 subrelease=13with C++ approach, minrelease=11, subrelease=43with Ada approach, minrelease=3, subrelease=15the less-interactions a project takes to pass the QA the best it is, so I can claim that in my experience a C++ project was usually approved with more internal activities on the draft version and more interactions with the QA team before a commitNote that a premium value for this is that Ada comes with better standard guidance and tools rules so it's usually approved by QA at the third attempt. This also thanks to Stood, a tool that is used to model the Ada core, so it's more consistent with the initial design. This makes good points for preferring it, even if ... the designing, planning, development, and testing usually takes a longer time than C, but not the time required by C++.

author: andyturk
author_rank: Frequent Contributor
timestamp: January 19, 2019, 04:59:30 pm
content: Quote from: legacy on January 19, 2019, 04:49:13 pmOh My God! That's horrible!</sarcasm>QuoteAda sounds like an ideal tool for the kind of work you do. Maybe you should start a thread on Ada?

author: cv007
author_rank: Frequent Contributor
timestamp: January 19, 2019, 05:23:12 pm
content: QuoteQuotethat's a lot of true/false stuff going on in there, probably not FAA approved.Since pseudo code doesn't need to pass any tests, I'm sure you could do your pseudo code to c++ (at least in this forum)-Code:Project myproject;while( not myproject.committed() ){ myproject.start_over() }we don't need to know what's in the Project process, and if we do you can show us the Project class.

author: legacy
author_rank: Super Contributor
timestamp: January 19, 2019, 07:45:43 pm
content: LOLyou made the trick, I do like it

author: legacy
author_rank: Super Contributor
timestamp: January 19, 2019, 07:57:15 pm
content: OOTiA is still the C++ challengeI have *zero* direct experience with space defense, but I know by having read a fifteen years ago paper where there was the name of the U.S. Federal Aviation Administration enlisting the National Aeronautics and Space Administration's support for a project called "Object-Oriented Technology" in Aviation, which went beyond just C++ issues.So they tried, and the project is where to look for identifying concerns about OOT relevant to safety and certification and object-oriented usage in safety-critical applications.It's kind of *guidance bible* to certification representatives who are approving object-oriented applications to DO-178B objectives.Fifteen years later ... we still have to be synched to the guidance. But don't panic, sooner or later ...

author: westfw
author_rank: Super Contributor
timestamp: January 21, 2019, 07:22:02 am
content: Quotehuh. I also see that std::array apparently wasn't added until C++11. ("Really? Are they kidding?!")

author: legacy
author_rank: Super Contributor
timestamp: January 21, 2019, 09:30:58 am
content: Quote from: hans on January 19, 2019, 03:19:21 pmlet's talk abouttools, static checkers, checking tools, et al: which tool do you use?

author: bogdant
author_rank: Regular Contributor
timestamp: January 21, 2019, 12:54:42 pm
content: So far seems to be a faith between microcontroller world and PC world. A project will work if developers knows the language used C or C++. The C++ is used in the PC applications but C is most like in OS side. We should use some of experience from PC and apply in the microcontroller since the are more more powerfull, and have more common projects external RAM and SD card attached. Is it possible?In the automotive also is used a subset of C99, constraind by MISRA rules. Should this be changed? It feels like I am 20 yeas into the past when I do programming at work. I am still wandering if I should start my home project stm32 based, in C++.Did someone face this challenge to transform one project that is already existing in C to C++?

author: cv007
author_rank: Frequent Contributor
timestamp: January 21, 2019, 02:40:22 pm
content: QuoteYou can wonder for a long time, but until you try it you will not know.

author: NorthGuy
author_rank: Super Contributor
timestamp: January 21, 2019, 03:18:33 pm
content: Quote from: bogdant on January 21, 2019, 12:54:42 pmI would definitely try it. That's the only way to see for yourself. I would re-write it (rather than porting) trying to utilize as much of new features as I can. It'll give you a better feel of what C++ is.