10 C language Skills for hardware engineers

Source: Internet
Author: User
Tags goto

The most common work of hardware designers is to test hardware by writing code. These 10 C language techniques (C language is still a common choice) can help designers avoid some defects caused by fundamental errors and cause maintenance problems.


In order to successfully launch a product, the software development process itself needs to experience countless practical risks and obstacles. The last thing any engineer wants is a challenge from the language or tool they use. Therefore, this requires the hardware designer to write code to test the working condition of the hardware, in the case of limited resources, also need to develop hardware and embedded software. Although tools and structured programming have made great strides, the usual choice is the C language, and the constant occurrence of fundamental errors can still cause some defects to occur and cause maintenance problems. To avoid these C programming pitfalls, there are 10 C language techniques for hardware engineers to refer to.


tip: Do not use "GOTO" statements


More than 20 years ago, when computer programming was still in its infancy, program flow was controlled by a "GOTO" statement. This class statement allows the programmer to break the current line of code and go directly to a different piece of code. Listing 1 is a simple example.



Listing 1 Using GOTO statements


The programming language eventually introduces the concept of a function that allows a program to break the code. If it is done, the GOTO statement is no longer used to indicate line breaks for the code. function calls, the function returns to the next instruction. Listing 2 is an example. This approach improves the program structure and improves readability. Since then, this is considered the correct way to write a program. As long as you see or think of the Goto statement, it will allow software engineers to shrink back, resulting in instinctive disgust. One of the main reasons is that a program spread over the goto statement makes it difficult to grasp the center of gravity, and does not facilitate understanding and maintenance of the program.




Listing 2 using a function to control the flow


Tip: use for (;;) or while (1)


If the goto statement is obsolete, then how to create an infinite loop on the program is a problem that some hardware engineers might be wondering about. After all, this is done by creating a goto statement and then returning to the main statement. The solution to this problem is to take advantage of the looping statements already existing in the C language for and while (listings 3 and 4).




Listing 3 uses an infinite for loop




Listing 4 uses an infinite while loop


The looping conditions in the list are relatively simple. For loops are simply using conditional statements with unconditional conditions. On the other hand, the while loop is executed as if the statement is true, which is equivalent to a non-0 value for any condition.


tip #3: Use the appropriate conditional statement


In addition to the readability of the code, the execution time of a program depends primarily on the type of conditional structure you choose to make the decision. Many hardware engineers are familiar with the use of simple if statements. However, sometimes an engineer may not realize that if the first condition is incorrect, you can also use the else or else if statement. This saves processor time without having to evaluate another conditional statement. In the first half of the code shown in Listing 5, if the Var value is 1, the code will still see if Var is 0. In the second half of the Else statement, the first statement is evaluated and then the following code continues, which saves the clock cycle and makes the code clearer.




Listing 5 replaces If/else with the only if


If/else if/else statements may not always apply. If you need to examine several possible conditions, the switch statement might be more appropriate. This allows the processor to evaluate the statement and then select the next action from an answer list without continuously evaluating a bunch of conditions. Listing 6 shows an example of the same type as the list 5 example.




Listing 6 using the switch statement


The moral of the above example is to make the selection of the conditional statement more open to select the most appropriate statement. This approach makes the program structure simpler, easier to understand the program flow, and shortens the processor's extra clock cycle. Tips #4: Avoid using assembly language


The natural language of the microprocessor is assembly language instruction. Programming for low-level machine languages may provide more efficient code for the processor. However, human beings are not born with this language, and experience has shown that writing assembly language can cause misunderstanding. Misunderstandings can lead to poor maintenance and, more likely, bugs throughout the system. General recommendation to avoid the use of assembly language. In fact, most compilers can now compile very efficient code. The use of C language or C + + language, such as advanced language development, can obtain a more orderly structure, easy to understand and maintain, so that the overall effect of the code better. Listing 7 shows an example that compares the assembly code and the C language code that is used to increment a 32-bit variable.



Listing 7 completes the increment of a variable with the assembly and the C language
Assembly
C code


Of course, there are still some occasions for using assembly language, but the situation is still relatively small. The first recommended occasion is the development of the boot loader program. In this case, you may need to optimize the speed of a decision (starting the Application or boot loader) during the startup process. At this point, the branching decision can be meaningful with assembly code. Another occasion is to develop a control loop that runs on a DSP with strict timing requirements. In order to get each clock cycle from the device, it is meaningful to do the coding of the control loop with assembly language. If the current task is appropriate for the compilation, it should be ensured that it is properly archived for easy availability, so that future developers (or future versions) will understand the purpose of the code.


skill #5: Make full use of modularity


The most common experience of the author is that a new project initiated by a hardware engineer is often a disorganized code organization. Usually we find that the code consists of a single main module, which has more than 25,000 lines of code. In these applications, everything is global, with few functions, and GOTO statements run through the entire code structure. This was normal 15 years ago, but it is no longer applicable. C language programming enables engineers to split code into separate functional modules, simplifying code navigation and enabling engineers to use object-oriented technologies such as encapsulation. It makes sense that the code can be organized into a logical module. Although it may take some time (a few minutes), in the long run, it will save a lot of long nights and many debugging pains.


tip #6: Write thousand-layer pie code instead of noodle code


Beningo is an Italian name and, like many Italians, I love pasta without reservation. When comparing pasta with software, I think of two kinds of pasta, spaghetti and lasagna. Spaghetti is more chaotic, the noodles are interwoven and criss-cross, and the result has no structure of any type at all. Writing unstructured code is very much like spaghetti: Take a bite and never know which part to eat.


The other is the Italian lasagna. This kind of pasta is layered and structured. Layered code is not only easier to understand, it can also remove a layer and add a new layer, basically can achieve the simplicity of reuse and maintenance. Figure 1 is an example of a simple software module using the thousand-layer pie code model.




Figure 1000 Layer Cake software model
Driver configuration
Application Configuration
Application
Driver Library
Hardware

Tip #7: Use descriptive variable names


There are many hurdles to writing larger software that is easy to understand and maintain, one of which is the naming conventions for variables. To try to shorten variable names, developers often create short, puzzling mnemonics, often symbols that only they can understand. Modern languages make a variable name can contain hundreds of characters. To make things clear, the "straightforward" approach is better than the other way. Therefore, the variable name at a glance is not only beneficial to developers, but also to the future maintenance team. Listing 8 shows an example.



List 8 Naming of variables


tips #8: Use less #pragma statements


There is a special #pragma statement in the C language. These statements typically deal with non-standard syntax and attributes and should be avoided as much as possible, since they are non-standard and cannot be ported from one processor to another. Some compilers may require such statements to accomplish a task, such as defining an interrupt service program. In this case, there may be no other way than to use the #pragma statement. If possible, put all the #pragma statements in one module or several modules. This helps ensure that only a few code updates, not the entire code base, need to be updated when the code is ported, and this will also help prevent the trouble of porting code's first compilation.


skill #9: Mistakes are not always as simple as they seem


When debugging a C program, one of the most cautious traps is compiler error. Because of the complexity of the compiler, when an error is detected, the error usually resides elsewhere in the program, rather than the location indicated by the compiler. This is primarily related to the steps of the compiler builder. Error types are usually consistent, and 90% of the errors that engineers can find are the root causes:

Beware of missing #include files. This may cause the program developer to see the perfect line of code, but the compiler flags it as an error because it does not contain the necessary header files, indicating that something is undefined.
Beware of missing a semicolon. The most common mistake when writing C code is to forget to add a semicolon at the end of the sentence.
Beware of missing brackets. The omission of parentheses is another common mistake in the code writing process, either inadvertently omitted, or an error character was generated because of a typing error.
Beware of missing commas. It's easy to forget commas in complex definitions.


In general, when a strange compile error dialog box pops up, you want to see what was compiled before the line. It's probably the wrong thing. It may be appearing on a line above, or in the middle, or in a completely different file.


Don't give up. As long as you have certain experience, solving these difficult problems will become a second nature.


tip #10: Good programmers don't necessarily write fewer lines of code


It is often misunderstood that a good programmer can solve a problem by writing fewer lines of code than a typical programmer. Don't get involved in the wrong idea. A good programmer usually has a thoughtful, structured coding base. Variable naming and encapsulation are all appropriate, and there are few global variables in the system. Functions should be kept short and valid. If your code looks messy, and you need to write a few more lines to make it look clearer, you might want to write a few more lines. The internet can be viewed as a cautionary tale for code that obtains the most confusing awards for C code writing. Good programmers write code that is concise, easy to understand and maintain, and not the least number of lines of code (Figure 2).



Figure 2 Short Program


Author Introduction

Jacob Beningo has acquired software engineering career certification (CSDP), specializing in the development and design of high-quality, robust embedded systems. He has a number of technical papers on embedded design methods, and teaches courses on programmable devices, bootloader and software methods. Beningo has a bachelor's degree in engineering physics from the University of Central Michigan (CMU) (Happy Hill Campus, Michigan) and a master's degree in Space Systems engineering from the University of Michigan (Ann Arbor, Michigan).


Note:

Ext: http://archive.ednchina.com/bbs.ednchina.com/BLOG_ARTICLE_3023219.HTM?click_from= 8800023178,9949745316,2014-08-18,edncol,newsletter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.