编程语言规范
- 格式:docx
- 大小:37.02 KB
- 文档页数:2
Linux C语言的编程规范(Linux)有独特的(编程)风格,在内核源代码目录Documentation/CodingStyle,详细描述代码风格。
建议大家可以去看一下,老外写技术文档还是很有意思的,上来就狂喷,“你不这样写就会完蛋,异教徒才不这样写……”,没有国内那么刻板,多阅读英语文档对技术增长很有帮助。
1. 命名规范在一般编程中,习惯以如下方式命名宏、变量和函数:#define (PI)3.1415926 /*用大写字母代表宏*/int minValue, maxValue; /*变量:第一个单词全小写,其后单词的第一个字母大写*/void SendData (void); /* 函数:所有单词第一个字母都大写*/ 这种通过单词之间通过首字母大写来区分的方式非常流行。
通过第1个单词的首字母是否大写可以区分名称属于变量还是属于函数,而看到整串的大写字母可以断定为宏。
许多领域的程序开发都遵照此习惯。
但是Linux不以这种习惯命名,对于上面的一段程序,在Linux中它会被命名为:#define PI 3.1415926int min_value, max_value;void send_data (void); 在上述命名方式中,宏还是一样用大写,但变量和函数名,不按照Windows所采用的用首字母大写来区分单词,而是采用下划线。
而且Linux下命名,全局变量命名最好用长的准确的描述,局部变量最好简短,甚至直接用tmp,i之类的。
其实两种命名方式都行,写Liunx下的程序时,与Linux社区代码风格一致更好,但你用第一种我觉得也无伤大雅。
2.缩进缩进统一使用"TAB",而不是空格括号。
另外提一句:在Linux下,"TAB"代表8个字符,而不是4个,Linux代码风格认为8个字符更能体现层次结构。
文档里喷"TAB"为4字符的是异教徒,对于8字符在多层次时,代码太偏右的问题,文档又喷层次超过三层,你的代码就会完蛋,哈哈哈。
C语言中的安全编码规则与规范C语言是一种广泛应用于软件开发的编程语言,然而,由于其强大的灵活性,C语言也有潜在的安全风险。
为了减少安全漏洞的发生,并确保编写的代码的质量与安全性,软件开发者需要遵循一些安全编码规则与规范。
本文将介绍C语言中常见的安全编码规则与规范,帮助开发者编写更安全、更可靠的代码。
1. 输入验证与过滤在C语言中,输入验证和过滤是保证安全的第一步。
开发者应该始终对外部输入数据进行验证,确保数据的类型、范围和长度符合预期。
特别是对于字符串输入,需要检查输入的长度,以防止缓冲区溢出攻击。
同时,还应该过滤输入数据,删除或转义特殊字符,以防止跨站脚本攻击或SQL注入等常见的安全威胁。
2. 内存管理与缓冲区溢出在C语言中,内存管理是一个关键的安全问题。
开发者应该注意使用动态内存分配函数(如malloc)时,合理管理内存的分配和释放,避免内存泄漏和悬挂指针等问题。
此外,必须非常小心操作缓冲区,确保不会发生缓冲区溢出。
使用安全的字符串操作函数(如strcpy_s和strncpy_s)来替代不安全的函数(如strcpy和strncpy),并确保缓冲区的大小足够。
3. 整数溢出与溢出检查在C语言中,整数溢出是一个常见的安全问题。
开发者应该对可能引发整数溢出的操作进行正确的检查和处理。
使用带符号整数进行算术运算时,要注意结果是否会溢出。
可以使用无符号整数或者增加运算结果的大小检查来避免整数溢出。
4. 随机数和加密安全的随机数生成对于密码学和安全敏感的应用程序至关重要。
C语言提供的rand函数并不是一个安全的随机数生成器,开发者应该使用操作系统提供的安全的随机数生成函数(如/dev/random或CryptGenRandom等)来生成随机数。
在进行加密操作时,也应该选择使用强大的加密算法,并遵循最佳实践来保护敏感数据。
5. 错误处理与异常处理在C语言中,适当的错误处理与异常处理是编写安全代码的一部分。
C C语言安全编程规范V公司内部编号:(GOOD-TMMT-MMUT-UUPTY-UUYY-DTTI-华为技术有限公司内部技术规范DKBA 6914-2013.05 C&C++语言安全编程规范2013年05月07日发布 2013年05月07日实施华为技术有限公司Huawei Technologies Co., Ltd.版权所有侵权必究修订声明本规范拟制与解释部门:网络安全技术能力中心本规范的相关系列规范或文件:《Java语言安全编程规范》《Web应用安全开发规范》相关国际规范或文件一致性:无替代或作废的其它规范或文件:无相关规范或文件的相互关系:本规范作为《C语言编程规范》和《C++语言编程规范》安全性要求的补充和扩展。
目录C&C++语言安全编程规范0规范制定说明0.1前言随着公司业务发展,越来越多的产品被公众、互联网所熟知,并成为安全研究组织的研究对象、黑客的漏洞挖掘目标,容易引起安全问题。
安全问题影响的不只是单个产品,甚至有可能影响到公司整体声誉。
产品安全涉及需求、设计、实现、部署多个环节,实现的安全是产品安全的重要一环。
为了帮助产品开发团队编写安全的代码,减少甚至规避由于编码错误引入安全风险,特制定本规范。
《C&C++语言安全编程规范》参考业界安全编码的研究成果,并结合产品编码实践的经验总结,针对C/C++语言编程中的字符串操作、整数操作、内存管理、文件操作、STL库使用等方面,描述可能导致安全漏洞或潜在风险的常见错误。
以期减少缓冲区溢出、整数溢出、格式化字符串攻击、命令注入攻击、目录遍历等典型安全问题。
0.2使用对象本规范的读者及使用对象主要为使用C和C++语言的开发人员、测试人员等。
0.3适用范围本规范适合于公司基于C或C++语言开发的产品。
0.4术语定义原则: 编程时必须遵守的指导思想。
规则:编程时必须遵守的约定。
建议:编程时必须加以考虑的约定。
说明:对此原则/规则/建议进行必要的解释。
C语⾔编程规范LDRA_MISRA_2004_Standard_v2[1].5.3_WebRules Definition Required AdvisoryTotal Implemented byLDRA 10317120Partially implemented byLDRA 617Not deemed to be statically analysable by atool12214NOTE: Of the 14 rules deemed 'Not statically analysable", a number of them are checkable to some extent with facilities available in the LDRA tool suite. This may be through the application of a related programming standard, or some other technique such as dynamic analysis.Total12120141This information has been compiled using version 7.7.1 of the LDRA tool suite and is correct as of July 2008.MISRA-C:2004 Coding StandardThe LDRA tool suite is developed and certified to BS EN ISO 9001:2000. This comparison has used the revised MISRA standard, MISRA-C:2004 "Guidelines for the use of the C language in critical systems" was published in October 2004.LDRA Ltd. reserves the right to change anyMISRA-C:2004Rule Required / Advisory LDRA Rule NumberMISRA Description LDRA Rule Description1.1Required293 S All code shall conform to ISO 9899:1990“Programming languages – C”, amended andcorrected by ISO/IEC 9899/COR1:1995, ISO/IEC 9899/AMD1:1995, and ISO/IEC 9899/COR2:1996.Non Ansi construct used.1.2Required412 SNo reliance shall be placed on undefined orunspecified behaviour.Undefined behaviour, \ before E-O-F.1.3Required N/AMultiple compilers and/or languages shall only be used if there is a common defined interfacestandard for object code to which thelanguages/compilers/assemblers conform.N/A1.4, 5.1Required 17 D The compiler/linker shall be checked to ensurethat 31 character significance and case sensitivityare supported for external identifiers.Identifier not unique within 31 characters. 1.5Advisory N/AFloating-point implementations should complywith a defined floating-point standard.N/A2.1Required 88 SAssembly language shall be encapsulated andisolated.Procedure is not pure assembler. 2.2Required 110 SSource code shall only use /* … */ stylecomments.Use of single line comment(s) //. 2.3Required 119 SThe character sequence /* shall not be usedwithin a comment.Nested comment found2.4Advisory 302 S Sections of code should not be “commented out”. Comment possibly contains code3.1Required N/AAll usage of implementation-defined behaviour shall be documented.N/A 3.2Required N/AThe character set and the correspondingencoding shall be documented.N/A3.3Advisory 373 S The implementation of integer division in thechosen compiler should be determined,documented and taken into account.Use of integer division 3.4Required69 SAll uses of the #pragma directive shall bedocumented and explained.#pragma used.LDRA Ltd. reserves the right to change anyMISRA-C:2004Rule Required / Advisory LDRA Rule Number MISRA Description LDRA Rule Description316 SBit field is not unsigned integral. 328 S Non bit field member in bitfield struct. 42 S Use of bit field in structure declaration. 226 S Bit field is not octal, hex or suffix u;3.6RequiredN/A All libraries used in production code shall be written to comply with the provisions of this document, and shall have been subject to appropriate validation.N/A4.1, 7.1Required 176 S Only those escape sequences that are defined inthe ISO C standard shall be used.Non standard escape sequence in source.4.2Required 81 S Trigraphs shall not be used.Use of trigraphs.384 S Identifier matches macro name in 31 chars.61 X Identifier match in *** chars. 5.2 - 5.5Required 131 S Identifiers in an inner scope shall not use the same name as an identifier in an outer scope,and therefore hide that identifier.Name reused in inner scope. 5.3, 5.6Required 112 STypedef name redeclared. 374 S Name conflict with typedef 16 X - 24 XIdentifier resuse: typedef vs …325 SInconsistent use of tag.4 X - 15 XIdentifier resuse: tag vs …18 D Identifier name reused 25 X - 39 XIdentifier reuse: ...91 S Name redeclared in another namespace (MR).40 X - 48 X Identifier reuse: ...5.6, 5.7Advisory383 S Identifier name matches macro name.Identifiers (internal and external) shall not rely on the significance of more than 31 characters.Required5.1Required 5.3 A tag name shall be a unique identifier.No identifier in one name space should have the same spelling as an identifier in another namespace, with the exception of structure and unionmember names.Advisory 5.63.5RequiredRequired 5.4Advisory 5.5If it is being relied upon, the implementationdefined behaviour and packing of bitfields shallbe documented.A typedef name shall be a unique identifier.No object or function identifier with static storage duration should be reused.LDRA Ltd. reserves the right to change anyMISRA-C:2004Required / Advisory LDRA Rule NumberMISRA Description LDRA Rule Description327 SReuse of struct member name. 49 X - 60 XIdentifier reuse: ...6.1Required 329 SThe plain char type shall be used only for thestorage and use of character values.Operation not appropriate to plain char. 93 S Value is not of appropriate type. 96 S Use of mixed mode arithmetic. 90 S Basic type declaration used. 495 S Typedef has no size indication6.4Required 73 SBit fields shall only be defined to be of typeunsigned int or signed int.Bit field not signed or unsigned int.6.5Required 72 S Bit fields of type signed int shall be at least 2 bitslong.Signed bit field less than 2 bits wide.7.1Required83 S Octal constants (other than zero) and octalescape sequences shall not be used.Octal number found.24 DProcedure definition has no associated prototype 8.2Required326 SWhenever an object or function is declared ordefined, its type shall be explicitly stated.Declaration is missing type.102 SFunction and prototype return inconsistent 103 SFunction and prototype param inconsistent 62 XFunction prototype/defn return type mismatch.63 XFunction prototype/defn parameter type mismatch.1 X Declaration types do not match across a system.360 S Incompatible type8.3RequiredFunction call with no prior declaration 496 S8.1Required8.4Required6.2, 12.1, 12.6RequiredAdvisory 6.35.7Advisory Functions shall have prototype declarations and the prototype shall be visible at both the function definitionIf objects or functions are declared more than once their types shall be compatible.Signed and unsigned char type shall be used only for the storage and use of numeric values.Typedefs that indicate size and signedness should be used in place of the basic types.No identifier name should be reused.For each function parameter the type given in the declaration and definition shall be identical, and the return types shall also be identical.LDRA Ltd. reserves the right to change anyMISRA-C:2004RuleRequired / Advisory LDRA Rule NumberMISRA Description LDRA Rule Description286 S Functions defined in header file. 287 SVariable definitions in header file. 8.6Required 296 S Functions shall be declared at file scope.Function declared at block scope. 8.7Required 25 DObjects shall be defined at block scope if theyare only accessed from within a single function.Scope of variable could be reduced26 D Variable should be defined once in only one file 60 DExternal object should be declared only once.172 S Variable declared multiply. 33 DNo real declaration for external variable.27 D Variable should be declared static61 D Procedure should be declared static 461 SIdentifier with ambiguous linkage.27 D Variable should be declared static 61 DProcedure should be declared static 8.12Required 127 S When an array is declared with external linkage,its size shall be stated explicitly or defined implicitly by initialisation.Array has no bounds specified.9.1Required 5 D All automatic variables shall have been assigneda value before being used.Procedure contains UR data flow anomalies.9.2Required105 S Braces shall be used to indicate and match thestructure in the non-zero initialisation of arrays and structures.Struct field initialisation brace fault.The static storage class specifier shall be used indefinitions and declarations of objects andfunctions that have internal linkage.RequiredAn external object or function shall be declared inone and only one file.Required 8.88.5Required There shall be no definitions of objects orfunctions in a header file.An identifier with external linkage shall haveexactly one external definition.Required 8.98.108.11RequiredAll declarations and definitions of objects or functions at file scope shall have internal linkage unless external linkage is required. LDRA Ltd. reserves the right to change anyMISRA-C:2004Rule Required / Advisory LDRA Rule NumberMISRA Description LDRA Rule Description9.3Required85 S In an enumerator list, the “=” construct shall notbe used to explicitly initialise members other than the first, unless all items are explicitly initialised.Incomplete initialisation of enumerator.93 S Value is not of appropriate type. 96 SUse of mixed mode arithmetic. 433 SType conversion without cast.(a) 434 S Signed/unsigned conversion without cast.(a) 435 S Float/integer conversion without cast.(a) 446 S Narrower int conversion without cast.(a) 488 SValue outside range of underlying type.(b) 452 SNo cast for widening complex int expression.(c) 458 SImplicit conversion: actual to formal param.(c) 491 S No cast for widening int parameter.(d) 101 S Function return type inconsistent.(d) 457 SImplicit int widening for function return. 93 S Value is not of appropriate type. 96 S Use of mixed mode arithmetic. 433 S Type conversion without cast.(a) 435 S Float/integer conversion without cast. (a) 445 S Narrower float conversion without cast.(b) 451 SNo cast for widening complex float expression.(c) 458 SImplicit conversion: actual to formal param.(c) 490 S No cast for widening float parameter.(d) 101 S Function return type inconsistent.(d) 456 S Implicit float widening for function return.Required10.2The value of an expression of floating type shall not be implicitly converted to a different type if:a) it is not a conversion to a wider floating type, orb) the expression is complex, or c) the expression is a function argument, or d) the expression is a return expression10.1RequiredThe value of an expression of integer type shallnot be implicitly converted to a differentunderlying type if:a) it is not a conversion to a wider integer type of the same signedness, orb) the expression is complex, or c) the expression is not constant and is a function argument, ord) the expression is not constant and is a returnexpression LDRA Ltd. reserves the right to change anyMISRA-C:2004Rule Required / AdvisoryLDRA RuleNumberMISRA DescriptionLDRA Rule Description93 S Value is not of appropriate type. 433 S Type conversion without cast.332 S Widening cast on complex integer expression. 442 SSigned integral type cast to unsigned.443 S Unsigned integral type cast to signed.444 SIntegral type cast to non-integral.93 S Value is not of appropriate type. 433 SType conversion without cast.333 S Widening cast on complex float expression. 441 SFloat cast to non-float.10.5Required334 SIf the bitwise operators ~ and << are applied to an operand of underlying type unsigned char orunsigned short, the result shall be immediately cast to the underlying type of the operand. No cast when ~ or << applied to small types.10.6Required 331 SA “U” suffix shall be applied to all constants ofunsigned type.Literal value requires a U suffix. 11.1Required94 S & 95 S Conversions shall not be performed between apointer to a function and any type other than anintegral type.Conversions shall not be performed between a pointer to a function and any type other than an integral type.11.2Required94 SConversions shall not be performed between a pointer to object and any type other than anintegral type, another pointer to object type or a pointer to void.Casting operation on a pointer.439 SCast from pointer to integral type.440 SCast from integral type to pointer.11.4Advisory95 S A cast should not be performed between apointer to object type and a different pointer toobject type.Casting operation to a pointer.11.3AdvisoryA cast should not be performed between a pointer type and an integral type.10.4RequiredThe value of a complex expression of integer type may only be cast to a type that is narrower and of the same signedness as the underlyingtype of the expression.Required10.3The value of a complex expression of floatingtype may only be cast to a narrower floating type.LDRA Ltd. reserves the right to change any MISRA-C:2004RuleRequired / Advisory LDRA Rule Number MISRA Description LDRA Rule Description203 SCast on a constant value.344 S Cast on volatile value. 96 SSee 6.2 above361 SExpression needs brackets.9 SAssignment operation in expression. 134 SVolatile variable in complex expression. 12.2, 12.3Required 35 D Expression has side effects.12.2, 12.4Required 1 Q Call has execution order dependant side effects.12.2, 12.13 Required 30 S Deprecated usage of ++ or -- operators found.12.3Required54 SThe sizeof operator shall not be used on expressions that contain side effects.Sizeof operator with side effects.406 S Use of ++ or -- on RHS of && or || operator. 408 SVolatile variable accessed on RHS of && or ||.12.5Required49 SThe operands of a logical && or || shall beprimary-expressions. The oparands of a logical && or || shall be primary-expressions .12.6, 13.2Advisory 114 SThe operands of logical operators (&&, || and !) should be effectively Boolean. Expressions thatare effectively Boolean should not be used as operands to operators other than (&&, || and !).Expression is not Boolean.50 SUse of shift operator on signed type.Bitwise operators shall not be applied to operands whose underlying type is signed.12.4Required 12.7Required11.5Required12.1AdvisoryA cast shall not be performed that removes any const or volatile qualification from the typeaddressed by a pointer.Limited dependence should be placed on C’s operator precedence rules in expressions.The value of an expression shall be the sameunder any order of evaluation that the standardpermits.The right hand operand of a logical && or ||operator shall not contain side effects.12.2Required LDRA Ltd. reserves the right to change anyMISRA-C:2004Rule Required / Advisory LDRA Rule NumberMISRA Description LDRA Rule Description120 S Use of bit operator on signed type. 12.8Required51 SThe right hand operand of a shift operator shall lie between zero and one less than the width inbits of the underlying type of the left hand operand.Shifting value too far.12.9Required 52 SThe unary minus operator shall not be applied toan expression whose underlying type is unsigned.Unsigned expression negated.12.10Required 53 S The comma operator shall not be /doc/9781b2552b160b4e767fcff3.html e of comma operator. 493 S Numeric overflow.494 SNumeric underflow.12.12Required 345 S The underlying bit representations of floating-point values shall not be used.Bit operator with floating point operand.12.13Advisory 30 S The increment (++) and decrement (--) operatorsshould not be mixed with other operators in anexpression.See 12.213.1Required 132 S Assignment operators shall not be used inexpressions that yield a Boolean value.Assignment operator in boolean expression.13.2Advisory 114 S Tests of a value against zero should be madeexplicit, unless the operand is effectively Boolean.See 12.613.3Required 56 S Floating-point expressions shall not be tested forequality or inequality.Equality comparison of floating point.13.4Required39 SThe controlling expression of a for statementshall not contain any objects of floating type.Unsuitable type for loop variable.429 SEmpty middle expression in for loop. 430 SInconsistent usage of loop control variable. 270 S For loop initialisation is not simple. 271 SFor loop incrementation is not simple.12.11Advisory Evaluation of constant unsigned integer expressions should not lead to wrap-around. operands whose underlying type is signed.The three expressions of a for statement shall be concerned only with loop control.13.512.7RequiredRequiredLDRA Ltd. reserves the right to change anyMISRA-C:2004RuleRequired / Advisory LDRA Rule NumberMISRA Description LDRA Rule Description13.6Required 55 D Numeric variables being used within a for loop foriteration counting shall not be modified in thebody of the loop.Modification of loop counter in loop body. 139 S Construct leads to infeasible code. 140 S Infeasible loop condition found.14.1Required1 J There shall be no unreachable code.Unreachable Code found.14.2Required57 S All non-null statements shall either :a) have at least one side-effect howeverexecuted, orb) cause control flow to change.Statement with no side effect.14.3Required 58 SBefore preprocessing, a null statement shall only occur on a line by itself; it may be followed by a comment provided that the first character following the null statement is a white space character.Null statement found.14.4Required 13 S The goto statement shall not be used.goto detected. 14.5Required 32 S The continue statement shall not be used.Use of continue statement. 31 SUse of break statement in loop. 409 SMore than one break statement in loop. 14.7Required 7 CA function shall have a single point of exit at theend of the function.Procedure has more than one exit point. 11 SNo brackets to loop body. 428 S No {} for switch. 14.9Required12 SAn if (expression) construct shall be followed by a compound statement. The else keyword shall befollowed by either a compound statement, or another if statement.No brackets to then/else.The statement forming the body of a switch, while, do ... while or for statement shall be acompound statement.For any iteration statement there shall be at most one break statement used for loop termination.Boolean operations whose results are invariantshall not be permitted.14.8Required14.613.7Required RequiredLDRA Ltd. reserves the right to change anyMISRA-C:2004RuleRequired / Advisory LDRA Rule NumberMISRA Description LDRA Rule Description59 S Else alternative missing in if.477 S Empty else clause following else if.60 SEmpty switch statement.385 S MISRA switch statement syntax violation.15.1, 15.5Required 245 S A switch label shall only be used when the mostclosely-enclosing compound statement is the body of a switch statement.Case statement in nested block.15.2Required62 S An unconditional break statement shall terminateevery non ?empty switch clause.Switch Case not terminated with break.48 SNo default case in switch statement.322 S Default is not last case of switch. 410 SSwitch empty default has no comment.15.4Required 121 SA switch expression shall not represent a valuethat is effectively /doc/9781b2552b160b4e767fcff3.html e of boolean expression in switch. 61 S Switch contains default only. 245 SCase statement in nested block.16.1Required 41 SFunctions shall not be defined with a variablenumber of arguments.Ellipsis used in procedure parameter list. 1 U Inter-file recursion found. 6 DRecursion in procedure calls found. 16.3Required 37 SIdentifiers shall be given for all of the parametersin a function prototype declaration.Procedure Parameter has a type but no identifier. 16.4Required 36 DThe identifiers used in the declaration anddefinition of a function shall be identical.Prototype and Definition name mismatch. 16.5Required 63 SFunctions with no parameters shall be declaredwith parameter type void.Empty parameter list to procedure/function. 21 S Number of parameters does not match.Every switch statement shall have at least onecase clause.Functions shall not call themselves, either directlyor indirectly.The number of arguments passed to a functionshall match the number of parameters.All if … else if constructs shall be terminated with an else clause.N/A15.5Required 16.2Required 14.10Required15.3Required16.6Required15N/AThe final clause of a switch statement shall bethe default clause.LDRA Ltd. reserves the right to change anyMISRA-C:2004RuleRequired / Advisory LDRA RuleNumberMISRA DescriptionLDRA Rule Description98 SActual and formal parameters inconsistent (MR).59 DParameter should be declared const.62 DPointer parameter should be declared const.2 DFunction does not return a value on all paths.36 S Function has no return statement. 66 S Function with empty return expression.16.9Required 99 S A function identifier shall only be used with eithera preceding &, or with a parenthesised parameter list, which may be empty.Function use is not a call.16.10RequiredDataflow anomalies If a function returns error information, then thaterror information shall be tested.N/A87 S Use of pointer arithmetic. 436 S Declaration does not specify an array.17.2Required438 SPointer subtraction shall only be applied topointers that address elements of the same array.Pointer subtraction not addressing one array.17.3Required 437 S >, >=, <, <= shall not be applied to pointer types except where they point to the same array.< > <= >= used on different object pointers.17.4Required 87 SArray indexing shall be the only allowed form of pointer arithmetic.See 17.117.5Advisory80 SThe declaration of objects should contain nomore than 2 levels of pointer indirection.Pointer indirection exceeds 2 levels.17.6Required 71 S The address of an object with automatic storage shall not be assigned to another object that may persist after the first object has ceased to exist.Pointer assignment to wider scope.465 S Struct/union not completely specified.481 SArray with no bounds in struct.17.1, 17.4RequiredAll exit paths from a function with non-void return type shall have an explicit return statement withan expression.Pointer arithmetic shall only be applied topointers that address an array or array element.A pointer parameter in a function prototype should be declared as pointer to const if the All structure and union types shall be complete at the end of a translation unit.Required16.8Required18.1Advisory16.7LDRA Ltd. reserves the right to change anyMISRA-C:2004Rule Required / Advisory LDRA Rule Number MISRA DescriptionLDRA Rule Description482 S Incomplete structure referenced.497 S Type is incomplete in translation unit.18.2Required 480 SAn object shall not be assigned to an overlappingobject.memcpy params access same variable.18.3Required N/A An area of memory shall not be reused forunrelated purposes.N/A18.4Required74 S Unions shall not be used. Union declared.75 S Executable code before an included file. 78 S Macro parameter not in brackets.338 S#include preceded by non preproc directives.19.2Advisory 100 SNon-standard characters should not occur inheader file names in #include directives.#include filename is non conformant. 292 SNo space between #include and filename. 339 S #include directive with illegal items. 427 SFilename in #include not in < > or " ". 19.4Required79 SC macros shall only expand to a braced initialiser, a constant, a parenthesisedexpression, a type qualifier, a storage class specifier, or a do-while-zero construct.Macro contains unacceptable items67 S #Define used in a block. 426 S #undef used in a block.19.6Required 342 SExtra chars after preprocessor directive. 19.6, 20.0Required 68 S#undef used. 19.7Advisory 340 SA function should be used in preference to afunction-like macro.Use of function like macro. 19.8Required 324 SA function-like macro shall not be invoked withoutall of its arguments.Macro call has wrong number of parameters. 19.9Required341 S Arguments to a function-like macro shall notcontain tokens that look like preprocessingdirectives.Preprocessor construct as macro parameter.Macros shall not be #define’d or #undef’d within ablock.#undef shall not be used.#include statements in a file should only bepreceded by other preprocessor directives orcomments.The #include directive shall be followed by eithera or "filename" sequence.the end of a translation unit.19.3Required19.5Required 19.1AdvisoryRequired18.1LDRA Ltd. reserves the right to change anyMISRA-C:2004RuleRequired / Advisory LDRA Rule NumberMISRA Description LDRA Rule Description19.10Required78 SIn the definition of a function-like macro each instance of a parameter shall be enclosed inparentheses unless it is used as the operand of # or ##.In the definition of a function-like macro the whole definition, and each instance of a parameter, shall be enclosed in parentheses or braces.19.11Required337 SAll macro identifiers in preprocessor directives shall be defined before use, except in #ifdef and#ifndef preprocessor directives and the defined() operator.Undefined macro variable in #if.19.12Required 76 SThere shall be at most one occurrence of the # or## operators in a single macro definition.More than one of # or ## in a macro. 19.13Advisory 125 S The # and ## operators should not be/doc/9781b2552b160b4e767fcff3.html e of ## or # in a macro 335 S operator defined contains illegal items. 336 S #if expansion contains define operator.19.15Required243 S Precautions shall be taken in order to prevent thecontents of a header file being included twice.Included file not protected with #define.19.16Required147 S Preprocessing directives shall be syntacticallymeaningful even when excluded by thepreprocessor.Spurious characters after preprocessor directive126 S A #if has no #endif in the same file.343 S #else has no #if, etc in the same file. 86 S Attempt to define reserved word. 156 S Use of 'defined' keyword in macro body. 478 S Misra special prefix banned name.20.2Required 218 SThe names of standard library macros, objectsand functions shall not be /doc/9781b2552b160b4e767fcff3.html is used in standard libraries. 20.3RequiredUnit TestingThe validity of values passed to library functions shall be checked.TBrun may be used to perform the necessary checks.Reserved identifiers, macros and functions in thestandard library, shall not be defined, redefinedor undefined.The defined preprocessor operator shall only beused in one of the two standard forms.All #else, #elif and #endif preprocessor directivesshall reside in the same file as the #if or #ifdef directive to which they are related.19.17Required19.14RequiredRequired20.1LDRA Ltd. reserves the right to change anyMISRA-C:2004。
什么叫规范?在C语言中不遵守编译器的规定,编译器在编译时就会报错,这个规定叫作规则。
但是有一种规定,它是一种人为的、约定成俗的,即使不按照那种规定也不会出错,这种规定就叫作规范。
虽然我们不按照规范也不会出错,但是那样代码写得就会很乱。
大家刚开始学习C语言的时候,第一步不是说要把程序写正确,而是要写规范。
因为如果你养成一种非常不好的写代码的习惯,代码就会写得乱七八糟,等到将来工作面试的时候,这样的习惯可能会让你失去机会。
代码如何写才能规范那么代码如何写才能写得很规范呢?代码的规范化不是说看完本节内容后就能实现的。
它里面细节很多,而且需要不停地写代码练习,不停地领悟,慢慢地才能掌握的一种编程习惯。
所以大家不要想着一下子就能把代码规范化的所有知识全部掌握,也不要想着一下子就能把代码写规范,这是不太可能的。
有很多知识,比如为什么代码要这样写,为什么不能那样写,作为一个初学者你是很难弄明白的。
有很多规范是为了在程序代码量很大的时候,便于自己阅读,也便于别人阅读。
所以刚开始的时候有很多规范你不知道为什么要那样规定,你就单纯地模仿就行了。
等将来敲代码敲得时间长了,你就会感觉到那样写是很有好处的。
代码规范化的好处代码规范化的第一个好处就是看着很整齐、很舒服。
假如你现在用不规范的方式写了一万行代码,现在能看得懂,但等过了三个月你再回头看时就很吃力了,更不要说给别人看了。
所以代码要写规范,比如加注释就是代码规范化的一个思想。
在一般情况下,根据软件工程的思想,我们的注释要占整个文档的20%以上。
所以注释要写得很详细,而且格式要写得很规范。
第二个好处是,把代码写规范则程序不容易出错。
如果按照不规范的格式输入代码的话,很容易出错。
而代码写规范的话即使出错了查错也会很方便。
格式虽然不会影响程序的功能,但会影响可读性。
程序的格式追求清晰、美观,是程序风格的重要构成元素。
代码规范化的七大原则代码规范化基本上有七大原则,体现在空行、空格、成对书写、缩进、对齐、代码行、注释七方面的书写规范上。
软件编程规范(MISRA_C)软件编程规范目录一环境二语言扩展三文档四字符集五标识符六类型七常量八声明与定义九初始化十数值类型转换十一指针类型转换十二表达式十三控制语句表达式十四控制流十五 switch语句十六函数十七指针和数组十八结构与联合十九预处理指令二十标准库二十一运行时错误一环境规则 1.1(强制):所有代码都必须遵照ISO 9899:1990 “Programming languages - C”,由ISO/IEC 9899/COR1:1995,ISO/IEC 9899/AMD1:1995,和ISO/IEC9899/COR2:1996 修订。
规则1.2(强制):不能有对未定义行为或未指定行为的依赖性。
这项规则要求任何对未定义行为或未指定行为的依赖,除非在其他规则中做了特殊说明,都应该避免。
如果其他某项规则中声明了某个特殊行为,那么就只有这项特定规则在其需要时给出背离性。
规则1.3(强制):多个编译器和/或语言只能在为语言/编译器/汇编器所适合的目标代码定义了通用接口标准时使用。
如果一个模块是以非C 语言实现的或是以不同的C 编译器编译的,那么必须要保证该模块能够正确地同其他模块集成。
C 语言行为的某些特征依赖于编译器,于是这些行为必须能够为使用的编译器所理解。
例如:栈的使用、参数的传递和数据值的存储方式(长度、排列、别名、覆盖,等等)。
规则1.4(强制):编译器/链接器要确保31 个有效字符和大小写敏感能被外部标识符支持。
ISO 标准要求外部标识符的头6 个字符是截然不同的。
然而由于大多数编译器/链接器允许至少31 个有效字符(如同内部标识符),因此对这样严格而并不具有帮助性的限制的适应性被认为是不必要的。
必须检查编译器/链接器具有这种特性,如果编译器/链接器不能满足这种限制,就使用编译器本身的约束。
规则1.5(建议):浮点应用应该适应于已定义的浮点标准浮点运算会带来许多问题,一些问题(而不是全部)可以通过适应已定义的标准来克服。
软件设计更多地是一种工程,而不是一种个人艺术。
如果不统一编程规范,最终写出的程序,其可读性将较差,这不仅给代码的理解带来障碍,增加维护阶段的工作量,同时不规范的代码隐含错误的可能性也比较大。
分析表明,编码阶段产生的错误当中,语法错误大概占20%左右,而由于未严格检查软件逻辑导致的错误、函数(模块)之间接口错误及由于代码可理解度低导致优化维护阶段对代码的错误修改引起的错误则占了一半以上。
可见,提高软件质量必须降低编码阶段的错误率。
如何有效降低编码阶段的错误呢?这需要制定详细的软件编程规范,并培训每一位程序员,最终的结果可以把编码阶段的错误降至10%左右,同时也降低了程序的测试费用,效果相当显著。
本文从代码的可维护性(可读性、可理解性、可修改性)、代码逻辑与效率、函数(模块)接口、可测试性四个方面阐述了软件编程规范,规范分成规则和建议两种,其中规则部分为强制执行项目,而建议部分则不作强制,可根据习惯取舍。
1.排版规则1程序块使用缩进方式,函数和标号使用空格缩进,程序段混合使用TAB和空格缩进。
缩进的目的是使程序结构清晰,便于阅读和理解。
<TAB>默认宽度应为8个空格,由于Word中<TAB>为4个空格,为示范清晰,此处用2个<TAB>代替(下同)。
例如:MOV R1, #00HMOV R2, #00HMOV PMR, #PMRNORMALMOV DPS, #FLAGDPTRMOV DPTR, #ADDREEPROMread1kloop:read1kpage:INC R1MOVX A, @DPTRMOV SBUF, AJNB TI, $CLR TIINC DPTRCJNE R1, #20H, read1kpageINC R2MOV R1, #00HCPL WDICJNE R2, #20H, read1kloop ;END OF EEPROM规则2在指令的操作数之间的,使用空格进行间隔,采用这种松散方式编写代码的目的是使代码更加清晰。
国际5种标准的PLC编程语言IEC1131-3为PLC制定了5种标准的编程语言,包括图形化编程语言和文本化编程语言。
图形化编程语言包括:梯形图(LD-Ladder Diagram)、功能块图(FBD - Function Block Diagram)、顺序功能图(SFC - Sequential Function Chart)。
文本化编程语言包括:指令表(IL-Instruction List)和结构化文本 (ST-Strutured Text)。
IEC 1131-3的编程语言是IEC工作组对世界范围的PLC厂家的编程语言合理地吸收、借鉴的基础上形成的一套针对工业控制系统的国际编程语言标准,它不但适用于PLC系统,而且还适用于更广泛的工业控制领域,为PLC编程语言的全球规范化做出了重要的贡献。
继电器梯形图(LD-Ladder Diagram)语言是PLC首先采用的编程语言,也是PLC最普遍采用的编程语言。
梯形图编程语言是从继电器控制系统原理图的基础上演变而来的,与继电器控制系统梯形图的基本思想是一致的,只是在使用符号和表达方式上有一定区别。
PLC 的设计初衷是为工厂车间电气技术人员而使用的,为了符合继电器控制电路的思维习惯,作为首先在PLC中使用的编程语言,梯形图保留了继电器电路图的风格和习惯,成为广大电气技术人员最容易接受和使用的语言。
梯形图程序设计语言的特点是:(1)与电气操作原理图相对应,具有直观性和对应性;(2)与原有继电器逻辑控制技术相一致,对电气技术人员来说,易于撑握和学习;(3)与原有的继电器逻辑控制技术的不同点是,梯形图中的能流(Power Flow)不是实际意义的电流,内部的继电器也不是实际存在的继电器,因此,应用时,需与原有继电器逻辑控制技术的有关概念区别对待;(4)与指令表程序设计语言有一一对应关系,便于相互的转换和程序的检查。
功能块图(FBD - Function Block Diagram)采用类似于数字逻辑门电路的图形符号,逻辑直观,使用方便,它有梯形图编程中的触电和线圈等价的指令,可以解决范围广泛的逻辑问题。
入门级程序员必学的10个代码规范代码规范是编写高质量、可维护和可扩展代码的重要指南。
遵循代码规范可以提高代码的可读性、降低维护成本,并促进团队合作。
以下是入门级程序员必学的10个代码规范:1.命名规范:-变量、函数和类名要有意义且描述性强,使用驼峰式命名法。
-避免使用单个字符或缩写作为变量名。
-对于常量,使用全大写命名,使用下划线分隔单词。
2.缩进和空格:-使用合适的缩进,一般为四个空格。
-避免使用制表符。
-为操作符和逗号之前添加空格,但不要在括号和参数之间添加空格。
3.注释规范:-在关键代码块上方添加注释,说明该代码的功能和用途。
-避免过度注释或乱写注释,只注释必要的部分。
-使用有意义的注释来解释复杂的算法或特殊需求。
4.函数和方法规范:-函数或方法的长度应保持在可读范围内,不要超过50行。
-函数和方法的功能应该单一,尽量避免实现过多的功能。
-使用合适的命名来描述函数或方法的功能。
5.错误处理:-使用异常处理机制来处理错误情况,避免使用错误码。
-函数和方法应该返回有意义的错误消息,方便用户调试和排查问题。
-在必要的时候,使用日志记录错误信息。
6.可复用性:-提取公共的功能代码到可复用的模块中,避免重复代码。
-使用接口或抽象类来定义通用的行为和方法。
-遵循单一职责原则,使每个类和方法只负责一个功能。
7.异步编程规范:-避免使用回调地狱,使用Promise、async/await等异步编程方法提高可读性。
-错误处理要考虑异步函数的特殊情况和回退机制。
8.文件和目录结构:-为文件和目录选择有意义的名称,符合项目的逻辑结构。
-放置相似功能或相关文件在同一文件夹下,方便查找和管理。
-确保代码和测试文件的分离,避免混淆。
9.版本控制:-使用版本控制系统(如Git)来管理代码的历史记录和变更。
-遵循合适的分支策略和提交规范。
-确保每个提交都有有意义的注释,解释变更的目的和影响。
10.代码审查:-将代码提交给同事或团队进行代码审查,以提供反馈和建议。
编程语言规范
编程语言规范是指规定了一个编程语言的语法和语义规则的文档。
它描述了如何正确地使用该语言来编写程序,并且定义了该语言的各种概念、语法结构、数据类型、操作和函数等。
编程语言规范通常包含以下几方面的内容:
1. 词法结构:规定了编程语言的关键字、标识符、常量和运算符的语法形式和规则。
例如,关键字是由特定的单词组成,标识符可以由字母、数字和下划线组成,常量可以是整数、浮点数和字符串等。
2. 语法规则:定义了编程语言的各种语法结构和语法规则。
例如,语法结构包括语句、表达式、函数定义和类定义等,语法规则定义了这些结构的组合方式和语法正确性。
3. 数据类型和操作:描述了编程语言支持的各种数据类型和相应的操作。
例如,整数、浮点数、布尔值和字符串等是常见的数据类型,而算术运算、逻辑运算和字符串操作是常见的操作。
4. 控制流和异常处理:定义了编程语言中控制程序执行流程的语法和语义规则。
例如,条件语句、循环语句和跳转语句等可以改变程序的执行路径,异常处理机制可以捕获和处理程序中的异常情况。
5. 函数和模块:描述了编程语言中函数和模块的定义和使用方式。
函数是可重用的代码块,模块是包含一组相关函数和数据
结构的代码单元。
函数和模块的定义和使用方式可以有多种方式,编程语言规范会规定一种或多种方式。
编程语言规范不仅仅是为了给程序员提供一个使用该语言编写程序的指南,它还为编译器和解释器提供了一个标准,使之能够准确地解析和执行程序代码。
编译器和解释器根据语言规范将程序源代码转换为机器可执行的形式,从而完成程序的编译和执行。
编程语言规范的编写需要考虑到语言的可读性、可靠性、灵活性和性能等方面的因素。
它应该简洁明了,使程序员能够轻松理解和使用语言的各种特性。
同时,它还要具备严密的逻辑结构,以确保程序的正确性和一致性。
总之,编程语言规范是一种重要的编程工具,它为程序员提供了一种准确和一致的方式来使用编程语言,并且为编译器和解释器提供了一个实现和执行语言的标准。
编程语言规范是编程语言发展和应用的基石,为程序员提供了丰富多样的编程工具和技术,促进了软件开发的进步和创新。