This is a document I wrote for the company a year ago to introduce young embedded software engineers on how to write high quality embedded C programs in a bare-metal environment. Feeling is a certain reference value, so take out to share, to give a thought.
Reprint please indicate the source: http://blog.csdn.net/zhzht19861011/article/details/45508029
Absrtact: Firstly, this paper analyzes the pitfalls and defects of C language, summarize the error-prone places, analyze the deficiencies of the compiler semantic check and give the preventive measures, take Keil MDK compiler as an example, introduce the compiler's characteristics, the treatment of undefined behavior and some advanced applications ; On this basis, this paper introduces the concept of defensive programming, puts forward a variety of measures that should be prevented in the process of programming, and puts forward the important role of testing in compiling high quality embedded programs and the common test methods. Finally, this paper tries to look at the higher level of programming and discuss some general programming ideas.
1. Introduction
There are many books about C language and programming method in the market, but there is little introduction to how to write high quality embedded C program, especially for the high quality C program writing method applied to MCU, ARM7, cortex-m3 and so on. This paper is aimed at the low-level programmers who use microcontroller, ARM7 and CORTEX-M3.
Writing high quality embedded C program is not easy, it is closely related to the designer's thinking and accumulation of experience. Embedded C programmers not only need to be familiar with the hardware features, hardware defects, but also in-depth language programming, not floating on the surface. For more convenient operation of the hardware, the compiler also needs to be in-depth understanding.
This article will discuss how to write high quality embedded C program from the aspects of language characteristics, compiler, defensive programming, test and programming ideas. Unlike many magazines and books, this article provides a large number of real examples, code snippets and bibliographies, not only about what to do, but also about how and why. Writing a high quality embedded C program involves a wide range, requiring programmers to accumulate a long period of experience, this article hopes to shorten the process.
2. C Language Features
Language is the cornerstone of programming, C language strange and there are a variety of traps and defects, the need for many years of experience to achieve a more perfect. Although there are many books, magazines, topics discussed in C language traps and defects, but this does not affect this section to discuss it again. There are always a large number of beginners, the successive pour in these traps and defects, civilian equipment, industrial equipment and even space equipment is no exception. This section will look at them again in the light of specific examples, hoping to attract sufficient attention. A deep understanding of C language features is the basis for writing high quality embedded C programs. 2.1 Everywhere is a trap 2.1.1 Unintentional
1) "=" and "="
The error of the comparison operator "= =" Into the assignment operator "=" may have been encountered by most people, such as the following code: [CPP] view plain copy print? 1. if (x=5) 2. {3.//other code 4. }
The code is meant to compare whether variable x equals constant 5, but mistakenly writes "=" as "=" and if statement is true. If an assignment operator appears in a logical judgment expression, most compilers now give a warning message. For example Keil MDK will give a warning note: "Warning: #187-D: Use of" = "where" = "may have been intended", but not all programmers will notice such warnings, so experienced programmers use the following code to avoid such Error:
[CPP] view plain copy print? 1. if (5==x) 2. {3.//other code 4. }
Place the constants on the left side of the variable x, and even if the programmer mistakenly writes ' = ' to ' = ', the compiler produces a syntax error message that no one can ignore: You cannot assign a value to a constant.
2) Compound assignment operator
Compound assignment operators (+ =, *=, and so on) although they can make expressions more concise and potentially produce more efficient machine code, some composite assignment operators also bring hidden bugs to the program, such as "+ +" easily mistakenly written as "=+", the code is as follows: [CPP] view Plain Copy print? 1. tmp=+1;
The code was meant to express tmp=tmp+1, but the compound assignment operator "= =" was mistakenly written as "=+": Assigning a positive integer constant of 1 to variable TMP. The compiler will gladly accept this type of code, and even warnings will not be generated.
If you can find this bug during the debugging phase, it should be celebrated, otherwise it is likely to become a major hidden bug and not susceptible to detection.
A similar problem exists with the compound assignment operator "=".
3 other easy to write using Chinese punctuation header File declaration statement last forget end semicolon logic with && and bit with &, logic or | | and bit or |, logically not. and bit by counter ~ Letter L and number 1, letter O and number 0
These errors are easy to be detected by the compiler, only to pay attention to the compiler on this message, you can quickly solve.
Many software bugs originate from input errors. When searching on google, some results list items contain a warning that Google thinks it has malicious code. If you use Google search in the early hours of January 31, 2009, you will see that in the 55 minutes that morning, Google's search results indicate that each site is harmful to your PC. This involves all sites across the Internet, including all of Google's own sites and services. Google's malware detection feature identifies dangerous sites by locating sites on a list of known attackers. On the morning of January 31, an update to this list accidentally contained a slash ("/"). All URLs contain a slash, and the Anti-malware feature understands that the slash is suspicious of all URLs, so it is pleasant to add a warning to each site in the search results. It is rare to see the result of such a simple input error so strange and so pervasive, but the procedure is this, without a trace of negligence. 2.1.2 Array subscript
Arrays are often also an important factor in the instability of the program, the C-language array of the confusion and the array subscript starting from 0 inseparable, you can define int test[30], but you can never use the array element test [30], unless you know exactly what you are doing. 2.1.3 Break keyword that is easily ignored
1 The break can not be missed plus
Switch...case statements make it easy to implement multiple branching structures, but note that you add the break keyword in the right place. Programmers tend to leak a break to cause sequential execution of multiple case statements, which may be a flaw in C.
For Switch...case statements, from the probability theory, most programs only need to execute a matching case statement at a time, and each one of these statement must follow a break. It's a little perverse to complicate a big probability event.
2) can not be indiscriminate break
The break keyword is used to jump out of the nearest loop or switch statement , but programmers often don't pay enough attention to it.
January 15, 1990, the At&t Telephone network in New York, a switch down and restarted, causing its proximity to the switch paralysis, interviewers, a connected, soon, 114 switches every six seconds downtime restart, 60,000 people within nine hours can not make long-distance calls. Solution at the time: the engineer reload the previous software version ... An accident investigation later found that this was caused by the misuse of the break keyword. "C Expert Programming" provides a simplified version of the problem source code:
[CPP] view plain copy print?