Embedded C programming skills _ programming style

Source: Internet
Author: User

Directory: 1. programming II. programming Skills 3. programming style /************************************* ******************* 1. programming cultivation-32 "accomplishments" in C language programming "*************************** * *************************/---------------------- 01, copyright and version 02, indentation, space, line feed, blank line, alignment 03, program comment 04, function [in] [out] parameter 05, system call return judgment 06, if statement for error handling 07, # ifndef 08 in the header file, memory allocation on the stack 09, variable initialization 10, use of H and C files 11, error information processing 12, calculation in common functions and loop statements 13, function name and variable name 14, function value passing and pointer Passing 15, modify others' program cultivation 16, put the same or almost identical Same code form function and macro 17, expression brackets 18, function parameter const 19, number of function parameters 20, function return type, do not omit 21. Use the GOTO statement 22. Use the macro 23. Use the static statement 24. The code size in the function 25. Use the typedef 26. Declare the macro as a constant 27. do not define the macro. + points 28, | and & statement execution order 29. Use for instead of while for loop 30 as much as possible. Please sizeof type instead of variable 31, do not ignore warning 32, write debug version and release version of the program 21, Goto Language Research hard 22, macro use 23, static use 24, function code size 25, typedef use 26, for the constant declare macro 27, do not define the statement execution sequence for the macro plus points 28, | and & 29, use for instead of while for loop 30, sizeof type instead of variable 31, do not ignore warning 32, write de Bug and release programs ------------------------ 1. copyright and version file: in top of file /********************************** **************************************** filename: filename. c ** Description :... ** Author: sharp_xiao, (time) 2007-04-05 ** version number: 1.0 ** Amend Notes: **************************************** * ********************************/function: in front function as/* ============================= ========================================================== =====** Name: xxx ** input: * type name [in]: descripts * output: * type name [out]: descripts ** description: *.............. ** return: * succed: True, failed: false ** pop abnormity: ** Author: sharp_xiao ====================================================== ========================================= */2. function pointers must first understand the following three problems: (1) in C, the number of letters directly corresponds to the address of the instruction code generated by the function in the memory. Therefore, the function name can be directly assigned to the pointing function (2) calling a function is actually equivalent to "transfer command + parameter transfer processing + regression position into the stack ", essentially, the core operation is to assign the first address of the target code generated by the function to the PC register of the CPU. (3) because the essence of function calling is to jump to the code of an address unit for execution, you can "call" a function entity that does not exist at all; eg. typedef void (* lpfunction) ();/* defines a */* function pointer type */lpfunction lpreset = (lpfunction) 0xf000fff0 with no parameters or return types; /* define a function pointer pointing to * // * the position of the First Command executed after the CPU is started */lpreset ();/* call the function */3. array. dynamic Application (1) Use arrays as much as possible, and arrays cannot be accessed across borders (if the truth goes over one step, it is a fallacy, And the array goes beyond the boundary to fulfill a chaotic embedded system); (2) if dynamic application is used, it must be determined after application No, the application is successful, and malloc and free should appear in pairs! That is, the principle of "who applies, who releases it. If this principle is not met, the coupling degree of the Code increases. eg. Change: char * function (void) {char * P; P = (char *) malloc (...); If (P = NULL )...;... /* A series of operations on p */return P;}... char * q = function ();... Free (Q); To: char * P = malloc (...); If (P = NULL )...; Function (p );... Free (p); P = NULL; void function (char * P ){... /* A series of operations on p */} 4. The keyword const (1) is used to send useful information to people who read your code. For example, adding the const keyword before a function parameter means that this parameter is not modified in the function body and is a "input parameter ". When there are multiple parameters, the function caller can clearly identify which are input parameters and which are possible output parameters based on whether the const keyword exists before the parameter. (2) the rational use of the keyword const can enable the compiler to naturally protect those parameters that do not want to be changed, so as to prevent them from being accidentally modified by code, so as to reduce the appearance of bugs. (3) const contains more meanings in the C ++ language. In C, const only means: "common variables that can only be read ", it can be referred to as "unchangeable variables" (This statement seems to be an easy-to-use, but most accurately expresses the essence of const in C ), the constants required in the compilation phase can only be defined in the # define macro! Therefore, the following program in C language is invalid: const int size = 10; char a [size];/* is invalid: variables cannot be used in the compilation phase. Only constants can be used to define the array length. */(4) in C ++ Class A {const int size = 100; // error, an attempt to initialize the const data member int array [size] in the class declaration; // error, unknown size}; the const data member initialization can only be performed in the class constructor initialization table, for example, Class A {A (INT size); // const int size;}; A: A (INT size): size (size) // The initialization table {} A (100) of the constructor; // The size value of object A is 100a B (200); // The size value of object B is 200 5. you can add the volatile keyword before the variable definition. Prevents the compiler from being optimized. volatile variables may be used in the following situations: (1) Hardware registers of parallel devices (for example, Status Registers, code in this example); (2) non-automatic variables (global variables) that will be accessed in an interrupt service subroutine; (3) variables shared by several tasks in a multithreaded application. Eg. optimize code: int A, B, C; A = inword (0x100);/* read the content of port 0 x of the I/O space and save it to variable A */B =; A = inword (0x100);/* read the content of port 0 x of the I/O space again and save it to variable A */C = A; as: int A, B, C; A = inword (0x100);/* read the content of port 0 x of the I/O space and save it to variable A */B = A; C = A; 6. program for debugging and release # ifdef debug void trace (char * FMT ,...) {......} # else # define trace (char * FMT ,...) # endif 7. try to use for instead of while for loop change: P = phead; while (p ){... P = P -> Next;} to: For (P = phead; P = p-> next ){..} 8. constant declare macro change: for (I = 0; I <120; I ++ ){....} to: # define max_usr_cnt 120 for (I = 0; I <max_user_cnt; I ++ ){....} eg.int user [120]; Use macro as the same 9. in general, a C project must do some work in this aspect, because you will involve cross-platform, different platforms will have different word lengths, so using pre-compilation and typedef allows you to maintain your code most effectively, as shown below: # ifdef solaris2_5 typedef boolean_t bool_t; # else typedef int bool_t; # endif typedef sh ORT int16_t; typedef unsigned short success; typedef int int32_t; typedef unsigned int success; # ifdef Win32 typedef _ int64 int64_t; # else typedef long int64_t; # endif typedef float float32_t; typedef char * string_t; typedef unsigned char byte_t; typedef time_t; typedef int32_t pid_t; other rules using typedef are that typedef is also recommended for structure and function pointers, this is also conducive to the ease of reading and maintainability of the program. 10. the code size of a function to complete a specific function. Generally, the code in a function should not exceed If there are about 600 rows, the fewer the better, the best function is usually within 100 rows, and the number of sunfunctions around 300 rows is almost the same. 11. the number of parameters of the function (use the structure when there are more parameters) is generally about 6. function parameters are passed from right to left in stack. 12. Name of the function and the name of the variable ------------ I have seen many programs rashly naming the variable and function names, especially the variable names, what a, B, c, AA, BB, CC, what other actions are flag1, flag2, cnt1, and cnt2. Even with a good note. Good variable names or function names should have the following rules: 1) They are intuitive and can be spelled out. They are expected to be informative and do not need to be decoded ". 2) the length of a name must be the shortest length, and its meaning must be expressed to the maximum extent. 3) do not use uppercase letters or lowercase letters. They must be in uppercase or lowercase, for example, getlocalhostname or useraccount. 4) It can be abbreviated but simplified to be clear, such as errorcode> errcode, serverlistener> servlisner, useraccount> usracct. 5) to avoid conflicts between global functions and variable names, you can add some prefixes, which are generally prefixed by the module abbreviation. 6) The global variable always adds a prefix or suffix to let people know that the variable is global. 7) use the Hungarian naming method to name function parameters and local variables. However, we still need to adhere to the "wangwen business" principle. 8) the naming style of the standard library (such as STL) or development library (such as MFC) is consistent. 13. ------- copyright and version ------- for C/C ++ files, the file header should have a comment similar to this: /*************************************** * ********************************** File Name: network. c ** file Description: created by Hao Chen in the network communication function set, February 3, 2003 ** version: 1.0 ** modification record: **************************************** * ********************************/for functions, there should also be annotations similar to this: /* ===================================================== =============================================== ** number of letters: xxx ** parameter :** Type name [in]: descripts ** Function Description :**.............. ** return value: true for success, false for failure ** throw an exception: ** OPERATOR: chenhao 2003/4/2 ** ========================================== ============================= *//********* **************************************** * ***** II. programming Skills --- (cultivation of C language Embedded System Programming) **************************************** */1 ). data Pointer unsigned char * P = (unsigned char *) 0xf000ff00; * P = 11; 2 ). function pointers must first understand the following three Question:. in C, the number of letters directly corresponds to the address of the instruction code generated by the function in the memory, so the function name can be directly assigned to the pointer to the function; B. calling a function is actually equivalent to "transfer commands + parameter transfer processing + regression position into the stack ", essentially, the core operation is to assign the first address of the target code generated by the function to the PC register of the CPU; C. because the essence of function calling is to jump to the code of an address unit for execution, you can "call" a function entity that does not exist at all. // "soft restart": 186 after the CPU is started, it jumps to the absolute address 0xffff0 (corresponding to the C language pointer 0xf000fff0, 0xf000 is the segment address, and 0xfff0 is the intra-segment offset) for execution, see the following code: typedef void (* lpfunction )(); /* define a no-parameter * // * function pointer type */lpfunction lpreset = (lpfunction) 0xf000fff0;/* define a function pointer, point to * // * CPU startup Position of the First Command executed after the operation */lpreset ();/* Call function */3) array. dynamic Application. use arrays as much as possible. arrays cannot be accessed out of bounds. B. if dynamic application is used, you must determine whether the application is successful after application, and malloc and free should appear in pairs! 4) The const keyword calls it "unchangeable variables". The constants required during the compilation stage can only be defined in the # define macro! Therefore, const int size = 10; char a [size];/* invalid: Variable */5 is not used in the compilation phase. The volatilevolatile keyword may be used in the following situations:. hardware registers of parallel devices (for example, Status Registers, code in this example); B. the non-automatic variables (that is, global variables) that will be accessed in an interrupt service subroutine; C. variables shared by several tasks in multi-threaded applications. 6) for macros, we need to know three points:. macro defines the "image" function; B. macro definition is not a function, so it needs to include all "Parameters"; C. macro definitions may cause side effects. Eg1. # define min (A, B) (a) <= (B )? (A): (B) // correct eg2.least = min (* P ++, B) ;=> (* P ++) <= (B )? (* P ++) (B) // unexpected events 7) the speed at which the CPU accesses various types of memory using hardware features is basically: CPU internal RAM> external synchronization Ram> external asynchronous Ram> Flash/Rom 8) Active bit operation 9) floating point variables cannot be compared with zero value floating point variables with "=" or "! = "Is compared with any number. Eg. if (x = 0.0) // comparison of implicit errors should be converted to: If (x> =-epsinon) & (x <= epsinon )) // epsinon is the allowable error (accuracy) 10) do not use sizeof (pointer ). because sizeof a pointer is just 4.eg: {char * Ch; memset (CH, 0, sizeof (CH); // there will make some crash issue} 11) notice memset or initialize the variable when define. 12) pointer to type T is not equivalent to array of type T. eg. an array: Char A [6] is defined in a source file. the extern char * A cannot be used for extern declaration in another file, but exter can only be used. N char a []; when using extern, it must strictly correspond to the declared format. ------------------------------------ summary in terms of performance optimization, always pay attention to 80-20 preparation, do not optimize the program to sell less than that 80%, this is reactive. --------------------------------------/************************************** ****************** 3. programming style --- C language ************************************ * ******************/1. see "programming" 2. naming Rule 1) function> [C ++: Class Name] is a combination of words starting with an upper-case letter. 2) local variables and parameters are combined with words starting with lowercase letters. 3) Add the global variable prefix G _ (global) .eg.int g_howmanypeople; // you can add prefix to global variables to avoid conflicts between global functions and variable names, generally, the prefix is "module abbreviation. 4) Statement variable-> static variable prefix S _ (static ). Eg. Static int s_initvalue; // static variable 5) const constant-> constants are all uppercase letters and words are separated by underscores. Eg. const int max_length = 100; 6) macro constants-> generally, uppercase letters are used. However, you can name a function based on naming rules. 7) data member> [C ++] class data member with a prefix of M _ (indicating Member). This prevents the data member from having the same name as the parameter of the member function. eg. void object: setvalue (INT width, int height) {m_width = width; m_height = height;} 8) The identifier should be intuitive and readable, you do not need to perform "decoding ". it is recommended that identifiers use English words or their combinations to facilitate memory and reading. 9) The length of the identifier must comply with the "Min-length & Max-Information" principle. 10) Naming Rules should be consistent with the operating system or development tool style. 11) do not show similar identifiers that are case sensitive only. Eg. int X, X, Z, Z; 12) do not show local variables and global variables with identical identifiers in the program. Although the scopes of the two are different, no syntax error occurs, but it may be misunderstood. 13) the variable name should use "noun" or "Adjective + noun ". Eg. {int oldvalue, newvalue;} 14) the name of a global function should be "verb" or "Verb + noun ). [c ++: The class member function should only use the "verb", and the omitted term is the object itself]. eg. drawbox (); // global function 15) name variables with mutex meanings or functions with opposite actions with correct antgroups. 16) do not include numbers in the name, such as value1 and value2, unless the numbers are indeed required logically. 17) to prevent conflicts between some identifiers in a software library and other software libraries, you can add prefixes that reflect the nature of software to various identifiers. For example, all library functions of 3D graphics standard OpenGL start with GL, and all constants (or macro definitions) start with GL. 3.1) if (null = xxx) // use value = xxx to avoid xxx = value {NULL; // use null when do nothing} 153102701421126198904103817
Related Article

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.