Coding Rule for C.docx
- 文档编号:29516815
- 上传时间:2023-07-24
- 格式:DOCX
- 页数:25
- 大小:24.76KB
Coding Rule for C.docx
《Coding Rule for C.docx》由会员分享,可在线阅读,更多相关《Coding Rule for C.docx(25页珍藏版)》请在冰豆网上搜索。
CodingRuleforC
TableofContents
1Naming4
1.1GeneralGuideline4
1.1.1Beaccurate4
1.1.2Usedescriptivenameforglobalsandshortnamesforlocals4
1.1.3NamingstyleshouldbeconsistwithOSordevelopmentenvironment4
1.1.4Avoidnamesthataresimilarordifferonlyincase4
1.1.5Avoidusingabbreviationsifpossible4
1.1.6Fortheabbreviationthatisgeneralpattern,usethelargeletters4
1.1.7Useterminologyapplicabletothedomain4
1.1.8Usethesamesymbolsasthenameintechnicaldatabookoruser'smanualfortheregisters.5
1.1.9Avoidlongnames(morethan31characters)5
1.2NamingFunctions5
1.2.1Add"static"keywordtoallfunctiondeclarationsiftheycanbestatic5
1.2.2Add“extern”keywordtoglobalfunctiondeclarations5
1.2.3Functionnameshoulduse“Verb”or“Verb+Noun”or“Verb+Adjective+Noun”style5
1.2.4Addprefix/postfixtoglobalfunction5
1.2.5Usetheprefixword‘is’forfunctionsthatreturnabooleanvalue5
1.2.6Complementnamesshouldbeusedforcomplementfunctions6
1.3NamingConstants6
1.3.1Constantsarenamedusingalluppercaseletters,wordsseparatedbyunderscores("_").6
1.3.2Addprefix/postfixtoglobalconstants6
1.4NamingVariables7
1.4.1Variablenameshoulduse“Noun”or“Adjective+Noun”style7
1.4.2Addprefix/postfixtoglobalvariables7
1.4.3NaminglocalvariablesafullEnglishdescription,exceptcommonabbreviations7
1.5NamingUser-definedTypes8
1.5.1User-definedtypesshouldbenamedtheexactsameconventionsasforvariables,andaddpostfix”_t”8
2Documentation9
2.1GeneralGuideline9
2.1.1WritethecommentsinEnglish9
2.1.2Documentwhysomethingisbeingdone,notjustwhat9
2.1.3Keepcommentssimple9
2.1.4Keepyourcommentasclearaspossible9
2.1.5Addcommentsonlywhenthecodealonedoesn’tprovideenoughinformation9
2.1.6Keepthosecommentsclosetothecodetowhichtheyrefer9
2.1.7Don’tcontradictthecode9
2.1.8Avoiddecoration,forexample,donotusebanner-likecomments9
2.1.9Okaytousephrasesinsteadofcompletesentences,intheinterestsofbrevity10
2.2CLanguageSpecificGuideline10
2.2.1Don’tuse‘//’stylecomment10
2.2.2Don’tnestcomments10
2.2.3Considerusing#if0...#endifwhenyouwanttocommentoutlargercodeblocks10
2.2.4Surroundyourcommentblockwithalineonlyhas"/*"and"*/"10
2.2.5IndentationofC-stylecommentblockwillbealignedwiththecodesdocumentedinthecomment10
2.3DocumentingFiles11
2.3.1Addacommentblockinthedefinedformatatthetopoffile11
2.4Copyrightstatement11
2.5DocumentingFunctions11
2.5.1Addacommentblockinthedefinedformatbeforefunctiondefinition11
2.5.2Functiondescriptionsshouldbeginwithaverbphrase12
2.6DocumentingConstants12
2.6.1Constantsshouldhaveanameexplainsitsrolewithoutcomments.Addcommentifitreallyneedsit.12
2.7DocumentingVariables12
2.7.1Addcommentsforglobalvariableswiththedeclarationordefinitionofthem12
2.7.2Avoidcommentsifpossibleforlocalvariables12
2.7.3Describewhatalocalvariableisusedforifitsnameisshorterorabbreviation12
2.8DocumentingUser-definedTypes12
2.8.1Beforeyouruser-definedtypedefinition,explainitspurpose12
3LayoutandStyle13
3.1GeneralGuideline13
3.1.1Pickastylethatsuitsyourproject,basedon"cultures"ofplatforms,librariesyouareusingfortheproject.13
3.1.2Usethestylethatisalreadyusedifyourevise/modify/addthesoftwaredevelopedbyothers13
3.1.3Considerandchoosewhatkindofthecodingstyleshouldbeappliedtoeachpartofyoursystem13
3.1.4Formatyourcodeusingthereformattingtoolsandintelligenteditors,notbyhand13
3.2Layoutforsourcefiles13
3.2.1Inyoursourcefile,placeyourcodeinorderdefined13
3.2.2Don'tskip"{"and"}"for1-linestatement13
3.2.3Keepthelengthofeachfunctiontolessthan100linesifpossible13
3.2.4Globalvariableshavetobedefinedanddeclareasexternalvariableinaheaderfile14
3.2.5switchstatement14
3.3Layoutforheaderfiles15
3.3.1Inyourheaderfile,placeyourcodeinorderdefined15
3.3.2Avoidhavingnestedincludes15
3.3.3Everyobjectandfunctiondeclarationinyourheaderfileshouldbeprecededbythekeyword“extern”15
3.4SAMPLESOURCE15
3.4.1Function15
3.4.2if-elseblock15
3.4.3forblock16
3.4.4do-whileblock16
3.4.5whileblock16
3.4.6switchblock16
3.4.7BitField16
References18
1
Naming
1.1GeneralGuideline
1.1.1Beaccurate
Anameisnotonlylabels,itconveysinformationtoreaders.[K&P99]
UsedescriptiveEnglishwordsorphrasefornames.Don’tusePinyin.Namingshouldbeaccurate.
GoodExample:
CurrentValue
BadExample:
NowValue
1.1.2Usedescriptivenameforglobalsandshortnamesforlocals
Globalsareusedanywhereinaprogram.Bycontrast,becauselife-cycleoflocalsisshorter,it’seasytounderstandtheirroleinthecontext.[K&P99]
1.1.3NamingstyleshouldbeconsistwithOSordevelopmentenvironment
Don’tcombinedifferentstylesinonecodingfile.
Windowsexample:
DeviceName,MaxValue
Linuxexample:
device_name,max_value
1.1.4Avoidnamesthataresimilarordifferonlyincase
BadExample:
intx,X;
voidfoo(intx);
voidFOO(intx);
1.1.5Avoidusingabbreviationsifpossible
Maintaintheabbreviationlistandusethemconsistently,ifyouwanttousethem.[Ambler00]
Ifyouwanttousingabbreviationforalongname,chooseoneanduseitconsistently.Don’tusedifferentabbreviationforasamename.
GoodExample:
CounterabbreviatetoCnt
intgHourCnt,gMinCnt,gSecCnt;
BadExample:
intgHourCnt,gMinCont,gSecCntr;
1.1.6Fortheabbreviationthatisgeneralpattern,usethelargeletters
GoodExample:
RAM,ROM,LCD,LED,OSD,UART,DMA,SIO,SPI,I2C,I2S
1.1.7Useterminologyapplicabletothedomain
Ifyourusersrefertotheirclientsas"customers",thenusetheterm"Customer"fortheclass,not"Client".Manydeveloperswillmakethemistakeofcreatinggenerictermsforconceptswhenperfectlygoodtermsalreadyexistintheindustryordomain.[Ambler00]
Onlyonetermshouldbeusedforasingleconcept.[K&P99]
1.1.8Usethesamesymbolsasthenameintechnicaldatabookoruser'smanualfortheregisters.
Example:
Specialfunctionregister,Databufferregister,Portfunction
Recommendation:
Usecommonheaderfiles
1.1.9Avoidlongnames(morethan31characters)
Programmersareoftenencouragedtouselongvariablenamesregardlessofcontext.Thisisamistake:
clarityisoftenachievedthroughbrevity.[K&P99][Ambler00]
InANSI/ISOCStandards,youcannotuseidentifiersmorethan31characterslong.[C90][C99]
1.2NamingFunctions
1.2.1Add"static"keywordtoallfunctiondeclarationsiftheycanbestatic
Astaticfunctionisafunctionthatcanbeusedonlybyotherfunctionsinthesamefile.
1.2.2Add“extern”keywordtoglobalfunctiondeclarations
AglobalfunctionisavisiblefunctiontoALLmodulesinaprogram.
1.2.3Functionnameshoulduse“Verb”or“Verb+Noun”or“Verb+Adjective+Noun”style
GoodExample:
intsave(FILE*);
intprint_label();
intread_pcm_data();
1.2.4Addprefix/postfixtoglobalfunction
Toavoidname-spacepollution,globalfunctionsshouldhaveashortprefix/postfix.Usuallyusemodulenameasprefix/postfix.
Therulesofthisprefix/postfixare:
∙Addaunderscore(‘_’)totheendoftheprefixorthebeginofpostfix
GoodExample:
intsio_save(FILE*);
intsio_print_label();
intread_pcm_data_AUDIODRV();
1.2.5Usetheprefixword‘is’forfunctionsthatreturnabooleanvalue
GoodExample:
intis_switch_on(intswitch);
1.2.6Complementnamesshouldbeusedforcomplementfunctions
GoodExample:
intset_value();
intget_value();
table1CommonComplementFunctionNames
Complementnames
Situation
get/set
returnvalue/modifyvalue
add/remove
add/removeaitemto/fromacollection
create/delete
allocate/freeareaandinitialize/finalizeobjects
start/stop
start/stopanactivity(e.g.threads)
insert/erase
add/removeaitemto/fromacollection
open/close
initialize/finalizedevices
read/write
read/writedatafrom/tofiledescriptors
show/hide
changevisible/invisible
increment/decrement
countup/down
acquire/release
acquire/releaseresourceownership
lock/unlock
acquire/releaseresourceownership
send/receive
send/receivedatabetweenmodules
construct/destroy
construct/destroyobjects
connect/disconnect
connect/disconnectcommunicationchannels
1.3NamingConstants
1.3.1Constantsarenamedusingalluppercaseletters,wordsseparatedbyunderscores("_").
InClanguage,constantsmeanmacros,constdeclarationsandenumerationdeclarations.
GoodExample:
#defineTRIGGER_LVEL(16)
staticchar*DEVICE_NAME="UART01\n";
enumtask_state{
TASK_STATE_READY,
TASK_STATE_RUN,
TASK_STATE_WAIT
};
1.3.2Addprefix/postfixtoglobalconstants
Toavoidname-spacepollution,globalconstantsshouldhaveashortprefix/postfix.Usuallyusemodulenameasprefix/postfix.
Therulesofthisprefix/postfixare:
∙Describetheprefix/postfixusinguppercasecharacters
∙Addaunderscore(‘_’)totheendoftheprefixorthebeginofpostfix
GoodExample:
typedefenum_tagUARTLB_CH{
UARTLB_CH_00,
UARTLB_CH_01,
UARTLB_CH_02,
UARTLB_CH_03,
UARTLB_CH_MAX
}UARTLB_CH;
1.4NamingVariables
InClanguage,therearefourkindsofvariables:
∙Alocalvariableisvariablesdefinedinablockorfunctionscope.
∙Astaticvariabledefinedinafunctioncanbeusedonlyinthefunction.
∙Astaticvariabledefinedinafilecanbeusedonlybyfunctionsinthefile.
∙AglobalvariableisvisibletoALLmodulesinaprogram.Itdeclareswiththe‘e
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Coding Rule for