6

I am usually a wood worker and not a developer. I'm learning C/C++ for embedded systems while trying to make some of my tool autonomous to save me hours of repetitive work.

For now, its fun and going well, I have spend maybe a hundred of hours coding/learning and already saved more time*.

As I want to keep going is buying and following MISRA coding rule a "mandatory good idea"? What does MISRA contain? Only coding rules, or kind of tips to make it safer?

Those tools could be dangerous (after all they cut wood and a human body is far less resistant...).

Note: I obviously do my test in 4 steps:

  1. Just the pic running with an OSD & SD card logger (one day I'll make an anylze tool and stop reading those).

  2. I plug the tool with nothing on it

  3. I use soft drill/cutters on foam

  4. I conduct real test at good distance with my hand on the emergency stop button.

Also I'm the only employee and no one else has access to my work-place.

*for now I've turn a drill into a kinda 3D wood printer (doing the not precise part of the work), and a "cutter-board" into an automated one.

Note2: I'm not a native speaker so tools' names are probably off.

Toby
  • 9,696
  • 16
  • 68
  • 132
A.albin
  • 274
  • 2
  • 15
  • 2
    MISRA can give you warnings of a bad code, and it may help, but it's not a magic wand. You need start being wood worker **and** developer, and understand your code. C has a concept of *undefined behaviour*, which means that code can behave any way it wants if there is such flaw. So don't trust the code that *seems* to work; only trust code that you *know* will work. – user694733 Apr 24 '17 at 13:11
  • 1
    @user694733 it might be odd but I dont really trust computers, after all code is mine so... I only use my code if on 30 hours of logs I dont have a single ouput out of +5% of the expected values. My question is more: Will Misra rules help me to do a better code, or is it more addressed to companies as a kinda of flag they can show to their costumers? – A.albin Apr 24 '17 at 13:15
  • 1
    MISRA is a set of coding rules, but better read the explanations for each rule and take it as recommendations. I.e. know when the follow them and when they are nonsense. Some of the rules make the code more unsafe than without them, e.g. for requiring casts. – too honest for this site Apr 24 '17 at 13:44

2 Answers2

8

MISRA is designed originally for use in the automotive industry, though it has grown well past that at this stage. The MISRA guidlines stated aims are:

  • Ensure safety
  • Bring in robustness, reliability to the software.
  • Human safety must take precedence when in conflict with security of property.
  • Consider both random and systematic faults in system design.
  • Demonstrate robustness, not just rely on the absence of failures.
  • Application of safety considerations across the design, manufacture, operation, servicing and disposal of products.

The documents mainly consist of rule based advisory information for code that tries to meet these aims. MISRA document prices have dropped somewhat over the years, some documents can be bought online from MISRA for as little as GBP £10 + VAT.

However, as a beginner and amateur coder, I would advise first bolstering your knowledge of C and C++. While in most areas of industry it is often good to follow a pertinent standard, if applicable, the documents are written with the assumption that the reader has a very solid grounding in the languages and also in the concerns and processes governing full-scale commercial type applications written in them. If your workshop is for personal use only, and depending on rules governing workplace safety in your jurisdiction, I can say that having a good understanding of the languages, language tools and the hardware would allow you to start making good choices with regards to how to code things more-so than reading MISRA could at such a stage in.

As commented above, and it is worth reiterating, MISRA is not some kind of magic wand or concrete way of going about things that will guarantee your code is good, works and is safe. Both good and bad code can meet standards. Following MISRA before having a good and complete grasp of what you are doing might be the same as ensuring every cable in your work shop is neatly tacked in place but then stabbing yourself with a chisel.

Toby
  • 9,696
  • 16
  • 68
  • 132
  • So, for now its not "mandatory", but at some point it might really be a nice idea to look for it. Also I checked the price and its definetly not an issue. – A.albin Apr 24 '17 at 13:18
  • Definitely not mandatory. While following it for any program wouldn't hurt, its main use that I know of is for applications with which companies have the need to demonstrate that their code conforms to that level of safet. Taking a real life example this might imply that an incorrectly coded function hopefully *shouldn't* cause the brake on 1000's of cars to become ineffectual – Toby Apr 24 '17 at 13:21
  • Some of the rules actually result in bad code and inhibit compiler checks. – too honest for this site Apr 24 '17 at 13:46
  • @Olaf Possibly you've worked with MISRA-C:2004 or older. The rules regarding implicit type conversions were improved quite a bit in the 2012 version. It is more focused on which types that are safe to convert between, rather than dogmatically "casting to the underlying type" as was done in older MISRAs. – Lundin Apr 24 '17 at 13:49
  • 1
    @Lundin: It was the older version. But IIRC, it still forbids certain compiler-extensions which actually make the code safer. gcc`s `-fplan9-extensions` come into mind which are definitively against MISRA. Personally I find it a good reading, but a good programmer should follow it not religiously. A bad programmer will not really write better code with it. Too bad many companies (especially automotive) treat it like a religion with "no good other than MISRA" and the people which design company guidelines don't have enough knowledge to understand the problems.. – too honest for this site Apr 24 '17 at 13:52
  • 1
    @Olaf It is indeed quite qualified work to write the company guidelines according to MISRA-C. Ideally you'd have at least one hardened C veteran (10+ years of experience) in charge of the document. I think this is where most companies go wrong, following MISRA-C and their (buggy) static analysers blindly - which is a dangerous thing to do. MISRA-C does the most good when you get a warning from the tool, then stop and think "what is this rule trying to tell me?". Meaning you would ideally have to read and understand the rationale for the rule in order to follow it (or ignore it). – Lundin Apr 24 '17 at 14:12
  • @Lundin: That's what I say: take it as a good and condensed reading to get ideas what can go wrong in C. Problem is most companies have static MISRA-C coding guidelines, so you cannot make exceptions in a project. As one example: the simple `*p++` is not really harmfull; there is often no use for using index-operator instead. This can result in less performing code, especially on small MCUs where commerial compilers are required. Such compilers are often a decade or more behind the optimisations of modern compilers like gcc. This makes applying MISRA even worse. – too honest for this site Apr 24 '17 at 14:18
  • 4
    "a good programmer should follow it not religiously" - sound advice. My main problem with all of these programming rules is that they encourage complacency and discourage thinking. – JeremyP Apr 24 '17 at 14:26
  • @Olaf `*p++ + *p++` is however harmful and undefined behavior. There is a very sound MISRA rule that bans the use of the `++` operators together with other operators. Code such as `while(a++ = b++)` is a typical example of "wannabe-idiomatic C" which is actually nothing but obfuscation. It could be rewritten in several lines, with identical machine code but more readable code as a result: `a=b; while(a) { a=b; a++; b++; }` – Lundin Apr 24 '17 at 14:30
  • @Lundin: Problem is here there are still (very expensive) commercial compilers whicl will generate really awful code. One result of such problem is using 32 bit dual-cores where an 8-bit single core would suffice. (Ironically the compiler used for the big iron might generate optimised code). And I disagree `*p++ = *q++` is less readable. Any read of code is expected to know the language syntax, grammar and semantics. Coding only for beginners results in code worsening from one generation to the next, ending eventually in C-pidgin. – too honest for this site Apr 24 '17 at 14:36
  • @JeremyP And on the other side, a set of formal, canonical rules bans rotten, personal coding agendas and "artist" or caveman behavior. They ban subjective things like: "programming is art" or "in order to understand this trick I just invented you must be really smart and join the private club of privileged people", but also arrogant opinions such as "I am right and everyone else is wrong, the vast majority of all other programmers be damned." Such behavior is admittedly a much much bigger problem for the software industry than people dogmatically following coding standards. – Lundin Apr 24 '17 at 14:39
  • @Lundin: Programming **is** a creative act. However, like music, there are compositions which are just offending good taste. The art is not that much in the text itself, but the whole implementation, as much as a single tone of chord does not make a masterpiece. Much more important than following a ruleset cast in concrete is a consistent coding style. That already forbids getting too creative, as such constructs are specific for a certain snippet. But that discussion leads too far, I think we are not really too far with what we mean. – too honest for this site Apr 24 '17 at 14:48
  • @Lundin The statement I quoted from Olaf was qualified with "a **good** programmer". No set of rules is going to stop the kind of programmer you describe (aka **bad** programmer) from producing bad code. – JeremyP Apr 24 '17 at 14:50
  • @Olaf No, programming is more like a craft than an art. – JeremyP Apr 24 '17 at 14:51
  • @JeremyP: Maybe I should have used "software development". Coding is only 10% of software development. roughly 30-50% is testing (depending on the field of application and the company ;-), the rest is art. If architecture is art, software development is it, too. At least if you don't work on standard software. If you're stuck with the latter, I feel with you. It's similar to a painter of pictures and a house-painter. – too honest for this site Apr 24 '17 at 16:30
  • @Lundin: I would consider me quite a good software developer, including programmer. But in my field and working for different companies, it is often _problematic_ to use my own coding style. Does that make me not good programmer? I don't think so. In those projects I could use my own style, no one has complained until now; opposite experienced colleagues can typically work into my code-base quite well. And that's the target. See above about beginner-style coding. I agree about macro-exesses, but the other way, avoiding macros _under all circumstances_ is also bad style. – too honest for this site Apr 24 '17 at 16:37
  • @Olaf I still disagree with you. Software development should be engineering but it is closer to being a craft (in the sense of. artisanal craft, not witchcraft!). – JeremyP Apr 25 '17 at 09:05
  • @JeremyP: You have to look at the whole field, not your (as I understand from your profile) field of desktop/mobile development. Embedded development e.g. **is** definitively engineering, if you don't work in a tight cast like AUTOSAR, but ae the one who defines the project (to a certain extend). Of course like all tasks, a great (likely major) part is standard work, but that's not different from a composer or songwriter or creative picture-painter. In one aspect Lundin is right: one should get too creative with expressions, but that is general advice, nothing related to a specific construct. – too honest for this site Apr 25 '17 at 09:48
  • This might be a candidate comment stream for moving to chat maybe guys? :-) – Toby Apr 25 '17 at 10:04
  • 1
    @Olaf My Dad (qualified heavy electrical engineer) laughs when people describe writing computer programs as "engineering". The best we can say is that we aspire to being engineers and and maybe the limited world of embedded programming is closer than most other areas. – JeremyP Apr 26 '17 at 08:31
  • @JeremyP: Your dad would be surprised how much analog components have been replaced by ADCs, DACs and DSP algorithms. For example special switching power supplies are today built around a MCUs which incorporates the regulation algorithms. I talked about embedded systems **as a whole system**. This includes electroncs as well as software. It is not really a difference if you build a regulation loop with analog components or software. Just that the latter is more complex and has more variables typically. Maybe your dad should leave the 1970ies and inform himself? (btw: I am an EE) – too honest for this site Apr 26 '17 at 12:37
  • @Olaf No he wouldn't. First of all, you assume he doesn't keep up to date. Secondly I said he was a heavy electrical engineer. He works in electrical power distribution. If it's less than 10kV he isn't bothered. But that isn't the point, in the software world, we are nowhere in terms of good solid practices as compared to other engineering disciplines. That's not being critical, it's being honest and it's not surprising, our trade has only been around for about 70 years. Even electronics has been around for a lot longer than that. – JeremyP Apr 26 '17 at 12:57
  • @JeremyP: Even such systems use digital regulation algorithms more and more. If he keeps up with the development. And I talked about the whole field. You pick raisins from a cake to find something (you think) my statement does not apply and think they cover all. But software development is a very wide field, from almost full artistic fields like computer art to standard software, from software architects, system designers to the house-painters for standard software and maintenance or software documentation. You really need to get a broader picture and learn to differentiate. – too honest for this site Apr 26 '17 at 13:03
  • From where I stand, you are talking about embedded programming and I am talking about general purpose computing. My experience - which is considerable in the field of computing generally - is that we are still in the days where we don't really know what we are doing. The activity of building a system is craft work, not engineering. We've gone on too long. You can have the last word, but my non reply should not be taken as conceding defeat. – JeremyP Apr 26 '17 at 14:34
3

MISRA-C is a set of rules which will enforce you to weed out well-known problems and poorly-defined behavior from a C program. It is a "safe subset" of the C language, banning various forms of dangerous practice through rules aiming for well-known bugs such as reliance on poorly-defined behavior or implicit type conversions. C has the advantage of being a very old language, meaning that all the language flaws are well-known.

MISRA-C has a heavy focus on static code analysis to find bugs at compile-time. This is something to keep in mind, as to my knowledge there exists no open source static code analyser tools that can check for MISRA-C compliance. The commercial tools tend to be very expensive and often also full of bugs/false positives. Still, most of them are useful.

MISRA-C is only focused on C programming, it does not address CPU or microcontroller issues etc, although it does enforce some forms of defensive programming, which is a counter against EMI, run-away code and other forms of unexpected program behavior. (For a list of general tips & tricks beyond C, see this. Not all of these will necessarily apply to your specific machine though.)

To demonstrate MISRA compliance, you create a "compliance matrix" which shows how you catch every directive/rule of the MISRA-C document: through compiler messages, peer review, static code analysis etc.

Most rules in the document make a lot of sense, but some do not. MISRA-C does however allow deviations from most rules, ranking them as one of:

  • Mandatory. No deviations allowed.
  • Recommended. One must invoke a formal deviation procedure if not following the rule.
  • Advisory. One can deviate from the rule without making a formal deviation.

Typically, creating MISRA-C compliance is therefore done by establishing a company coding standard, which addresses all rules. The easiest way to implement it is write down in this document which rules that are followed and which ones that are skipped, on a company level. Then set static code analysis filters accordingly.

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • An open-source tool that can check for MISRA-C 2012 compliance was recently released: it is a python addon for Cppcheck called "misra". – fripon Apr 05 '18 at 15:19