C code and debug this section Tutorial mainly introduces a good C code style, how to write secure code and program debugging technology in the Visual C environment, these contents have gradually participated in the actual project for new employees Developing work, and reading third party codes. 1 Specifies the classification of software development at the current phase of the class, relying on the team's cooperation. Programmers are no longer synonymous with personal heroism, and the programmer should rely on the code to complete in a large number of other programmers. On the one hand, there is a large number of code to use other people, and the code actually has two elements: first is a reliable supply. Some function, followed by clearly expressing the author's thoughts. Any communication must have a certain specification to perform, reflecting in the code is to understand. In addition, standardizable code is reusable, and the standard code has longer life, with better maintainability, more convenient for later expansion. 1.1 How to make a good code of the good code is easy to understand, reflecting countless arguments in the details, in fact regardless of style and habits, good code has several common characteristics: 1. Good name : Good variable names and function names, let the people who read the code immediately know the variable or function's role, it is easy to understand the procedures and functions of the program. The programmer must understand the Hungarian nomenclature. 2. Consistency: Consistency brings better procedures, consistent code indent style can display the structure of the code, which indent style is not important, in fact, the specific code style is far from using them. important. 3. Note: The comment is a means of helping the program readers, and the program author is also one of the future program readers. The best note is the highlighter characteristics of the program, or provide an overview to help others understand the procedure; but if the comment is just something that is already toned, or confused with the code, or confused Interfering with the reader, that is, helping to go.
1.2 Developing good habits have been mentioned before, and the specific code style is far from using them. Therefore, put too much energy is placed in the choice of A or B is wasting time, you have to do it. How to write a code that is easy to understand, how to develop good habits, below is some tips. 1. Name the variable and function in accordance with Hungarian naming method. 2. Follow the international popular code style. 3. Write code while following your naming norms and writing style, don't remedy afterwards. 4. Use the tool (Parasoft C Test) to check your code, and evaluate yourself to form a good habit. 5. Adhere to indirectly to develop habits. 2 Write a safe and reliable code In a large application software system, each code snippet constitutes a complete system. The interaction between the code is very frequent. The program crashes often do not occur when the error occurs, but delayed for a while, after passing After the transfer between functions, it will take time when positioning and looking for errors, how to reflect errors in the program in time, how to avoid some naive semantic errors in the code? A function tends to be used by other programmers, but how can he use the function written by other people? This part of the content can help solve these problems.
2.1 The idea of contracting programming programming programming in C Bible class, C 's parent Bjarne Stroustrup "C programming language" in the "C programming language" of the OO, the Bible "Object-Oriented Software Construction" The big balance has released the contract programming. Now more software developers recognize the importance of contract programming and gradually adopt contract programming in actual work. A simple interpretation of the contract programming is: Define a contract between the implementation of the code block (function, class) to the implementation call condition (constraint) and output results, define a contract between the functionality and the caller. Specifically to our work, developers should define contracts for each function and class that is completed. The contract programming seems to be free, there is no specific help to the program development. In fact, the contract programming can maximize the reliability and security of the software in the development phase. In actual work, whenever you need to use the modules provided by other programmers, you don't know how to call, and don't know if the parameters you have entered are legal. Sometimes I can't believe in the processing results of the function module. These should have a significant information, because the module provider has no explicit provision, causing the caller only touching the stone crossing the river, and wasting a lot of time, and in order to make your code more secure, do it in the code A large number of judgment and assumptions, resulting in damage to the code structure and the loss of efficiency, and finally, the caller still does not ensure that its call is correct. The contract programming is clearly defined between functional providers and calorifications to avoid the above situation, ensuring code quality and software quality between functional providers and calibrators. 2.2 Active debugging Active Trial Note When you write a code, help us quickly pop the message box when the software error occurs, inform the developer error, and abort the program. These debugging code is only effective in the Debug version, and when fully tested, the Release version is issued, these debug code automatically invalidates. Active debugging and contract programming complements each other, and jointly guarantee the quality of software development. The contract programming is equivalent to various contracts signed in economic life, and active debugging is equivalent to legal punishment measures taken by some parties without complying with contracts.
Both various development language and development tools provide these debug statements, and standard C provides an ASSERT function. The MFC provides an ASSE RT debug macro help us to actively debug. In actual work, it is recommended to uniformly use the MFC's ASSERT debugging macro. 2.2.1 Parameter Check For written functions, in addition to a clear specified contract, the incoming parameters should be checked at the beginning of the function, ensuring that the illegal parameters are immediately reported immediately. For example: Bool getPathitem (INT ILEN) {Assert (I> 0); assert (null! = Szitem); assert ((ilen> 0) && (ilen Complete checks should be as follows: // An example of completely checking the error condition BOOL EnumerateListItems (PFNELCALLBACK pfnCallback) {ASSERT (FALSE == IsBadCodePtr (pfnCallback));} 2.2.2 internal check proper use ASSERT code for bug The detection and improvement of debugging efficiency have great help, and a simple example will be explained below. Switch (NTYPE) {CASE GK_ENTITY_POINT: // Do Something Break; case gk_entity_pline: // do something break; default: assert (0);} In the above example, the switch statement only processes GK_ENTI Two cases of TY_POINT and GK_ENTINTITY_PLINE should be that they only need to handle these in the system, but if the later system needs to process more cases, and this part of the code is not updated in time, or because the developer is negligent missed. A bug that may cause system misorosis or crash, and use Assert to remind the developer's negligence and eliminate this bug as quickly as possible. There are also situations that when developers write code, if it is confident that A occurs in a certain point A is wrong, then you can add Assert, exclude A. In summary, appropriate, flexible use of ASSERT to actively debug, greatly improve the stability and security of the program, reduce debugging time, and improve productivity. 2.3 Useful code style Some good code style can also help you avoid some naive, low-level errors, and this error is hard to detect. Due to the simple and flexible characteristics of C language, it is sometimes improving a character, or a character, it is possible to make a big disaster, and this error is not gradually gradually with your programming level and experience. Avoid, everyone will be knocked, right. For example, programmers will often be equal to logic judgment == false knocked assignment operators =, I will not discover after I don't likely the program is running. Because my habits are, for logic judgment, set constants to == Left, if I entered =, then the compiler will report an error. IF (int_max == i) 3 Visual C debugging technology Check code until the dizzy flower does not find errors, a running program will crash, have to sacrifice the last magic: Debugger. The Visual C debugger can be called the best C / C debugger under the Windows platform, and the Visual C debugger can also debug programs written in other languages such as Delphi, Java, which can be powerful. Although the Visual C debugger has such a big power, it can only help you find some hidden logical errors, which is powerless for programming and structural defects. The most commonly used Visual C debugging technology of programmers has set breakpoints, tracking call stacks, and dismissive debugging, other compiler functions are auxiliary tools in debugging, because the reverse tune requires programmers to have assembly language knowledge and language underlayer structure Here, here is no longer introduced. 3.1 Prerequisites of debugging Professional debuggers have a common feature that they are also excellent developers. Obviously, if you are not an excellent developer, you can't be a debug expert, and vice versa. The following is a high level, at least a qualified commodes or developers need to be proficient. 1. Understand the project: The understanding of the project is the first element of preventing user interface, logic, and performance errors. Understand how various functions are implemented in various source files, and where you implement, you can reduce the lookup range and find out the problem. 2. Master the language: Master the language used by the project, the debugger (developer) must know how to program these languages, and know what these languages do in the background. 3. Master the technology: To solve the problem, the first important step is to seize the essentials of the technology used, this does not mean that you have to be a clear, but you should use it. The technology has a probably understanding, and more importantly, when you need more detailed information, you should know where to find it. 4. Operating system and CPU: Any project is actually running in a specific operating system and a specific CPU, the more the operating system knows, the greater the search error help; in theory, master assembly language, you can debug resolution Any bug. Regardless of doing work, as long as it is often engaged in technical work, you must constantly learn to keep up with the development of technology, not to say that you want to do better or want to walk in the forefront of technology development. I often read excellent technical books and magazines, and write more practical procedures. Read other outstanding developers' code, do some anti-assessment work, will effectively help you improve the development and commissioning level (especially when you put these four organic combines these four ). 3.2 Debugging Process Determines a certain difficulty for the debugging process suitable for solving all errors, but the debugging process proposed by John Robbins should be the most practical: 1. Copy error 2. Description error 3. Always assume that the error is your own problem 4 Decompose and resolve the error 5. Thinking on creating 6. Using debug auxiliary tools 7. Start debugging work 8. Check errors have been corrected 9. Learning and communicating Describe the error to help correct the error, and can also get the help of colleagues. Gradually reduce the scope of the problem, exclude the code segment that does not exist until the problem is found, is a universal applicable method for all issues. Some strange mistakes require you to transfer your sight from code heap to other aspects such as operating systems, hardware environments. Good use of various debug auxiliary tools to save you a lot of time, and some tools themselves will not give you a chance to have some mistakes. When you solve a bug, stop thinking, what caused you (or him), how to avoid it in the future? To remember that the debugger is just a tool, it is better than a screwdriver. You let it do, what is only doing, the real debugger is the debugging idea in your own brain. 3.3 Breakpoints and their usage In the Microsoft Visual C debugger, set a breakpoint in the source line. Just open the source file, put the cursor on the code line you want to set the breakpoint, press the F9 shortcut, and press the F9 shortcut again to cancel the breakpoint. When running the code line, the debugger will stop at the set location. This simple location breakpoint is extremely powerful. After statistics, only a separate use of this breakpoint can solve 99.46% debugging issues. If the program does not have an error every time it runs to the breakpoint, then keeps people who are getting tired of shuttles between the debuggers and applications, then the high-end breakpoints will be used. In essence, advanced breakpoints allow you to write some wisdom to breakpoints, so that when executed to breakpoints, only when the program internal status meets your designated conditions, interrupts Run and switch to the debugger. Press Alt F9 Shortcut to pop up the BreakPoints dialog box, browse the dialog, discover the dialog, divide the dialog, D ATA, and Messages three pages, respectively correspond to three breakpoints, respectively: Location breakpoint: We are usually used simply The point is a location breakpoint, and we can also set the breakpoint on a binary address or any function and enhance the function of the location breakpoint by specifying various qualified conditions. 2. Expression and variable breakpoint: The debugger will allow the program to run until the settings are met or the specified data changes. On the Intel CPU, both breakpoints use a hardware breakpoint as possible by the CPU's specific debug register. If the debug register can be used, the program will be able to run full speed, otherwise the debugger will perform a single step to perform each assembly instruction. Each step is checked, and the running speed of the program will be extremely slow or even unable to run. 3. Windows Message Breakpoint: Use the message breakpoint to let the debugger interrupt when the window process receives a specific Windows message. The message breakpoint is suitable for the C SDK type program. For programs such as the C class library such as MFC (which should be most), the message breakpoint is not practical, and the location breakpoint can be used to achieve the same effect. The settings of various advanced breakpoints have a detailed introduction in MSDN, and search the topic Using Breakp Oints: Additional Breakp Oints: Additional Breakp Oins: Additional Breakp Oins: Additional Information. 3.4 Call stack Sometimes we don't know where to set breakpoints, just know how the program is running suddenly, how to position at this time? The choice of this is to view the calling stack, call the stack to help us determine a specific timing, the mutual call relationship between each function in the program. The method is that when the program executes a breakpoint or the program crashes, the control is transferred to the debugger, press the Alt 7 shortcut, pop out the Call Stack window, you can see the current function call, the current function is on top The following function calls its above function. Select Parameter Values and Parameter Type S on the pop-up menu of the Call Stack window to display the parameter types and incoming values of each function. 3.5 Using Tracking Tools Some time, we want to understand the collaboration between different functions in the program, or due to the deletion of the document, it is desirable to confirm that the function is invoked when the function is called in different cases. At this time, it is too much trouble to use the breakpoint function, and the calling stack can only view the called condition of the current function, a better method is to use Trace Macros and a corresponding tool. Program (Debug Version) Once runs to the Trace macro, the TRAC E macro specified by the current Windows system is output to the current Windows system and display it when debugging the run (Press F5 key) program in the Visual C environment. When you can see the output content of the Trace macro at the debug page of the Output window. In fact, the Trace Macro is a function of encapsulating the Windows API function OutputDebugString. Some auxiliary tools can block the output content of the Trace macro in the clutch in the premise of the Visual C debugger, such as the "deep-in-depth MFC" appendix. Microsoft System Jou RNAL (MSJ) In January 1996, the TRACEWIN tool described in the C / C (in the older version of the MSDN) and the source code and documentation can be found) and the powerful free tool DebugView. With TRACE macros, we can easily understand the mutual collaboration relationships between the programs and the successful order and time of the call, further, you can fully grasp the execution process of the program. Finally, please note that Trace Hong will affect the efficiency of the program, so the currently used Trace macro is best deleted or comment. 4 Reading procedures Skills For programmers, whether it is learning or working, often read other programmatic source code, how to quickly understand the idea of the program, and inspect the structure of the program and various components, and further master the program Aspects involved, is a basic skill that the programmer is important. Here are some common techniques. 4.1 From the function, the interface starts a complete application or system consists of several relatively independent functions, which reacts on a graphical interface interacting with the user, is a variety of menu commands, toolbar button commands, and more. So if the current only is interested in the program, you can find the ID response functions of these menu commands, buttons commands, with this as the starting point, gradually go to the inside of the program until the function is fully understood. . The time spent on this process depends to a large extent on the level of programmers to the debugging technology. It is important to emphasize that in the case of unfamiliar with the core structure and implementation technology, the method directly adopts the process, when gradually depth to the core, the number of program modules involved will grow sharply, and the difficulty of understanding the difficulty will suddenly increase; Once you have the skill core structure and implementation technology, it will use this method to explore the procedure, and it will be like a feeling of broken bamboo.