chapter 25 embedded systems programming bjarne stroustrup

35
Chapter 25 Chapter 25 Embedded systems Embedded systems programming programming Bjarne Bjarne Stroustrup Stroustrup www.stroustrup.com/ www.stroustrup.com/ Programming Programming

Upload: dylan-adair

Post on 10-Dec-2015

257 views

Category:

Documents


8 download

TRANSCRIPT

Page 1: Chapter 25 Embedded systems programming Bjarne Stroustrup

Chapter 25Chapter 25Embedded systems programmingEmbedded systems programming

Bjarne StroustrupBjarne Stroustrupwww.stroustrup.com/Programmingwww.stroustrup.com/Programming

Page 2: Chapter 25 Embedded systems programming Bjarne Stroustrup

AbstractAbstract This lecture provides a brief overview of what This lecture provides a brief overview of what

distinguishes embedded systems programming distinguishes embedded systems programming from “ordinary programming.” It then touches from “ordinary programming.” It then touches upon facilities that become prominent or upon facilities that become prominent or problems when working “close to the problems when working “close to the hardware” such as free store use, bit hardware” such as free store use, bit manipulation, and coding standards. manipulation, and coding standards. Remember: not all computers are little grey Remember: not all computers are little grey boxes hiding under desks in offices.boxes hiding under desks in offices.

22Stroustrup/ProgrammingStroustrup/Programming

Page 3: Chapter 25 Embedded systems programming Bjarne Stroustrup

OverviewOverview Embedded systemsEmbedded systems What’s special/differentWhat’s special/different

predictabilitypredictability Resource managementResource management

memorymemory Access to hardwareAccess to hardware

Absolute addressesAbsolute addresses Bits – unsignedBits – unsigned

Coding standardsCoding standards

33Stroustrup/ProgrammingStroustrup/Programming

Page 4: Chapter 25 Embedded systems programming Bjarne Stroustrup

Embedded systemsEmbedded systems

Hard real timeHard real time Response must occur before the deadlineResponse must occur before the deadline

Soft real timeSoft real time Response should occur before the deadline most of the timeResponse should occur before the deadline most of the time

Often there are plenty of resources to handle the common casesOften there are plenty of resources to handle the common cases But crises happen and must be handledBut crises happen and must be handled

Predictability is keyPredictability is key Correctness is even more important than usualCorrectness is even more important than usual

““correctness” is not an abstract conceptcorrectness” is not an abstract concept ““but I assumed that the hardware worked correctly” is no excusebut I assumed that the hardware worked correctly” is no excuse

Over a long time and over a large range of conditions, it simply doesn’tOver a long time and over a large range of conditions, it simply doesn’t

44Stroustrup/ProgrammingStroustrup/Programming

Page 5: Chapter 25 Embedded systems programming Bjarne Stroustrup

Embedded systemsEmbedded systems

Computers used as part of a larger systemComputers used as part of a larger system That usually doesn’t look like a computerThat usually doesn’t look like a computer That usually controls physical devicesThat usually controls physical devices

Often reliability is criticalOften reliability is critical ““Critical” as in “if the system fails someone might die”Critical” as in “if the system fails someone might die”

Often resources (memory, processor capacity) are limitedOften resources (memory, processor capacity) are limited Often real-time response is essentialOften real-time response is essential

55Stroustrup/ProgrammingStroustrup/Programming

Page 6: Chapter 25 Embedded systems programming Bjarne Stroustrup

Embedded systemsEmbedded systems

What are we talking about?What are we talking about? Assembly line quality monitorsAssembly line quality monitors Bar code readersBar code readers Bread machinesBread machines CamerasCameras Car assembly robotsCar assembly robots Cell phonesCell phones Centrifuge controllersCentrifuge controllers CD playersCD players Disk drive controllersDisk drive controllers ““Smart card” processorsSmart card” processors

66

Fuel injector controlsFuel injector controls Medical equipment monitorsMedical equipment monitors PDAsPDAs Printer controllersPrinter controllers Sound systemsSound systems Rice cookersRice cookers Telephone switchesTelephone switches Water pump controllersWater pump controllers Welding machinesWelding machines Windmills Windmills Wrist watchesWrist watches ……

Stroustrup/ProgrammingStroustrup/Programming

Page 7: Chapter 25 Embedded systems programming Bjarne Stroustrup

Do You Need to Know This Stuff ?Do You Need to Know This Stuff ?

Computer Engineers – You will build and oversee the building of Computer Engineers – You will build and oversee the building of these systemsthese systems All “close to he hardware” code resembles thisAll “close to he hardware” code resembles this The concern for correctness and predictability of embedded systems code is The concern for correctness and predictability of embedded systems code is

simply a more critical form of what we want for all codesimply a more critical form of what we want for all code

Electrical Engineers – You will build and oversee the building of Electrical Engineers – You will build and oversee the building of these systems.these systems. You have to work with the computer guysYou have to work with the computer guys You have to be able to talk to themYou have to be able to talk to them You may have to teach themYou may have to teach them You may have to take over for themYou may have to take over for them

Computer scientists – you’ll know to do this or only work on web Computer scientists – you’ll know to do this or only work on web applications (and the like) applications (and the like)

77Stroustrup/ProgrammingStroustrup/Programming

Page 8: Chapter 25 Embedded systems programming Bjarne Stroustrup

PredictabilityPredictability

C++ operations execute in constant, measurable timeC++ operations execute in constant, measurable time E.g., you can simply measure the time for an add operation or a virtual E.g., you can simply measure the time for an add operation or a virtual

function call and that’ll be the cost of every such add operation and every function call and that’ll be the cost of every such add operation and every virtual function call (pipelining, caching, implicit concurrency makes this virtual function call (pipelining, caching, implicit concurrency makes this somewhat trickier on some modern processors)somewhat trickier on some modern processors)

With the exception of:With the exception of: Free store allocation (Free store allocation (newnew)) Exception Exception throwthrow

So So throw throw andand new new are typically banned in hard real-time are typically banned in hard real-time applicationsapplications Today, I wouldn’t fly in a plane that used thoseToday, I wouldn’t fly in a plane that used those

In 5 years, we’ll have solved the problem for In 5 years, we’ll have solved the problem for throwthrow Each individual Each individual throwthrow is predictable is predictable

Not just in C++ programsNot just in C++ programs Similar operations in other languages are similarly avoidedSimilar operations in other languages are similarly avoided

88Stroustrup/ProgrammingStroustrup/Programming

Page 9: Chapter 25 Embedded systems programming Bjarne Stroustrup

Ideals/aimsIdeals/aims

Given the constraintsGiven the constraints Keep the highest level of abstractionKeep the highest level of abstraction

Don’t write glorified assembler codeDon’t write glorified assembler code Represent your ideas directly in codeRepresent your ideas directly in code

As always, try to write the clearest, cleanest, most As always, try to write the clearest, cleanest, most maintainable codemaintainable code

Don’t optimize until you have toDon’t optimize until you have to People far too often optimize prematurelyPeople far too often optimize prematurely John Bentley's rules for optimizationJohn Bentley's rules for optimization

First law: Don’t do itFirst law: Don’t do it Second law (for experts only): Don’t do it yetSecond law (for experts only): Don’t do it yet

99Stroustrup/ProgrammingStroustrup/Programming

Page 10: Chapter 25 Embedded systems programming Bjarne Stroustrup

Embedded systems programmingEmbedded systems programming

You (usually) have to be much more aware of the resources You (usually) have to be much more aware of the resources consumed in embedded systems programming than you have consumed in embedded systems programming than you have to in “ordinary” programsto in “ordinary” programs TimeTime SpaceSpace Communication channelsCommunication channels FilesFiles ROM (Read-Only Memory)ROM (Read-Only Memory) Flash memoryFlash memory ……

You must take the time to learn about the way your language You must take the time to learn about the way your language features are implemented for a particular platformfeatures are implemented for a particular platform HardwareHardware Operating systemOperating system Libraries Libraries

1010Stroustrup/ProgrammingStroustrup/Programming

Page 11: Chapter 25 Embedded systems programming Bjarne Stroustrup

Embedded systems programmingEmbedded systems programming A lot of this kind of programming isA lot of this kind of programming is

Looking at specialized features of an RTOS (Real Time Looking at specialized features of an RTOS (Real Time Operating System)Operating System)

Using a “Non-hosted environment” (that’s one way of Using a “Non-hosted environment” (that’s one way of saying “a language right on top of hardware without an saying “a language right on top of hardware without an operating system”)operating system”)

Involving (sometimes complex) device driver architecturesInvolving (sometimes complex) device driver architectures Dealing directly with hardware device interfacesDealing directly with hardware device interfaces ……

We won’t go into details hereWe won’t go into details here That’s what specific courses and manuals are forThat’s what specific courses and manuals are for

1111Stroustrup/ProgrammingStroustrup/Programming

Page 12: Chapter 25 Embedded systems programming Bjarne Stroustrup

How to live without How to live without newnew

What’s the problemWhat’s the problem C++ code refers directly to memoryC++ code refers directly to memory

Once allocated, an object cannot be moved (or can it?)Once allocated, an object cannot be moved (or can it?)

Allocation delaysAllocation delays The effort needed to find a new free chunk of memory of a The effort needed to find a new free chunk of memory of a

given size depends on what has already been allocated given size depends on what has already been allocated

FragmentationFragmentation If you have a “hole” (free space) of size N and you allocate an If you have a “hole” (free space) of size N and you allocate an

object of size M where M<N in it, you now have a fragment of object of size M where M<N in it, you now have a fragment of size N-M to deal withsize N-M to deal with

After a while, such fragments constitute much of the memoryAfter a while, such fragments constitute much of the memory1212

Free space

New object

old object

old object

Stroustrup/ProgrammingStroustrup/Programming

Page 13: Chapter 25 Embedded systems programming Bjarne Stroustrup

How to live without How to live without newnew Solution: pre-allocateSolution: pre-allocate

Global objectsGlobal objects Allocated at startup timeAllocated at startup time

Sets aside a fixed amount of memory Sets aside a fixed amount of memory

StacksStacks Grow and shrink only at the topGrow and shrink only at the top

No fragmentationNo fragmentation Constant time operationsConstant time operations

Pools of fixed sized objectsPools of fixed sized objects We can allocate and deallocateWe can allocate and deallocate

No fragmentationNo fragmentation Constant time operationsConstant time operations

1313

Pool:

Stack:

Top of stack

Stroustrup/ProgrammingStroustrup/Programming

Page 14: Chapter 25 Embedded systems programming Bjarne Stroustrup

How to live without How to live without newnew No No newnew (of course) (of course)

And no And no malloc()malloc() (memory allocation during runtime) either (for those (memory allocation during runtime) either (for those of you who speak C)of you who speak C)

No standard library containers (they use free store indirectly)No standard library containers (they use free store indirectly) InsteadInstead

Define (or borrow) fixed-sized PoolsDefine (or borrow) fixed-sized Pools Define (or borrow) fixed-sized StacksDefine (or borrow) fixed-sized Stacks

Do not regress to using arrays and lots of pointersDo not regress to using arrays and lots of pointers

1414Stroustrup/ProgrammingStroustrup/Programming

Page 15: Chapter 25 Embedded systems programming Bjarne Stroustrup

Pool examplePool example

//// Note: element type known at compile timeNote: element type known at compile time//// allocation times are completely predictable (and short) allocation times are completely predictable (and short)//// the user has to pre-calculate the maximum number of elements neededthe user has to pre-calculate the maximum number of elements neededtemplate<class T, int N>class Pool {template<class T, int N>class Pool {public:public:

Pool();Pool(); // // make pool ofmake pool of N T N Ts – construct pools only during startups – construct pools only during startupT* get();T* get(); // // get aget a T T from the pool; return 0 if no free from the pool; return 0 if no free TTssvoid free(T*);void free(T*); // // return areturn a T T given out bygiven out by get() get() to the poolto the pool

private:private:// // keep track ofkeep track of T[N] T[N] array (e.g., a list of free objects) array (e.g., a list of free objects)

};};

Pool<Small_buffer,10> sb_pool;Pool<Small_buffer,10> sb_pool;Pool<Status_indicator,200> indicator_pool;Pool<Status_indicator,200> indicator_pool;

1515Stroustrup/ProgrammingStroustrup/Programming

Page 16: Chapter 25 Embedded systems programming Bjarne Stroustrup

Stack exampleStack example// // Note: allocation times completely predictable (and short)Note: allocation times completely predictable (and short)// // the user has to pre-calculate the maximum number of elements neededthe user has to pre-calculate the maximum number of elements neededtemplate<int N>class Stack {template<int N>class Stack {public:public:

Stack();Stack(); // // make anmake an N N byte stack – construct stacks only during startupbyte stack – construct stacks only during startupvoid* get(int N); // void* get(int N); // allocate n bytes from the stack; return allocate n bytes from the stack; return 00 if no free space if no free spacevoid free(void* p); void free(void* p); // // return the last block returned by return the last block returned by get() get() to the stackto the stack

private:private:// // keep track ofkeep track of anan array of array of NN bytes (e.g. a top of stack pointer) bytes (e.g. a top of stack pointer)

};};

Stack<50*1024> my_free_store;Stack<50*1024> my_free_store; // // 50K worth of storage to be used as a stack50K worth of storage to be used as a stack

void* pv1 = my_free_store.get(1024);void* pv1 = my_free_store.get(1024);int* pi = static_cast<int*>(pv1);int* pi = static_cast<int*>(pv1); // // you have to convert memory to objectsyou have to convert memory to objects

void* pv2 = my_free_store.get(50);void* pv2 = my_free_store.get(50);Pump_driver* pdriver = static_cast<Pump_driver*>(pv2);Pump_driver* pdriver = static_cast<Pump_driver*>(pv2);

1616Stroustrup/ProgrammingStroustrup/Programming

Page 17: Chapter 25 Embedded systems programming Bjarne Stroustrup

TemplatesTemplates

Excellent for embedded systems workExcellent for embedded systems work No runtime overhead for inline operationsNo runtime overhead for inline operations

Sometimes performance mattersSometimes performance matters No memory used for unused operationsNo memory used for unused operations

In embedded systems memory is often critical (limited)In embedded systems memory is often critical (limited)

1717Stroustrup/ProgrammingStroustrup/Programming

Page 18: Chapter 25 Embedded systems programming Bjarne Stroustrup

How to live with failing hardwareHow to live with failing hardware Failing how?Failing how?

In general, we cannot knowIn general, we cannot know In practice, we can assume that some kinds of errors are more common than In practice, we can assume that some kinds of errors are more common than

othersothers But sometimes a memory bit just decides to changeBut sometimes a memory bit just decides to change

Why?Why? Power surges/failurePower surges/failure The connector vibrated out of its socketThe connector vibrated out of its socket Falling debrisFalling debris Falling computerFalling computer X-raysX-rays ……

Transient errors are the worstTransient errors are the worst E.g.E.g., only when the temperature exceeds 100° F. and the cabinet door is closed, only when the temperature exceeds 100° F. and the cabinet door is closed

Errors that occur away from the lab are the worstErrors that occur away from the lab are the worst E.g.E.g., on Mars, on Mars

1818Stroustrup/ProgrammingStroustrup/Programming

Page 19: Chapter 25 Embedded systems programming Bjarne Stroustrup

How to live with failing hardwareHow to live with failing hardware ReplicateReplicate

In emergency, use a spareIn emergency, use a spare Self-checkSelf-check

Know when the program (or hardware) is misbehavingKnow when the program (or hardware) is misbehaving Have a quick way out of misbehaving codeHave a quick way out of misbehaving code

Make systems modularMake systems modular Have some other module, computer, part of the system Have some other module, computer, part of the system

responsible for serious errorsresponsible for serious errors In the end, maybe a person In the end, maybe a person i.e., i.e., manual override manual override Remember HAL ? Remember HAL ?

Monitor (sub)systemsMonitor (sub)systems In case they can’t/don’t notice problems themselvesIn case they can’t/don’t notice problems themselves

1919Stroustrup/ProgrammingStroustrup/Programming

Page 20: Chapter 25 Embedded systems programming Bjarne Stroustrup

Absolute addressesAbsolute addresses Physical resources (Physical resources (e.g.e.g., control registers for external devices) , control registers for external devices)

and their most basic software controls typically exist at and their most basic software controls typically exist at specific addresses in a low-level systemspecific addresses in a low-level system

We have to enter such addresses into our programs and give a We have to enter such addresses into our programs and give a type to such datatype to such data

For exampleFor exampleDevice_driver* p = reinterpret_cast<Device_driver*>(0xffb8);Device_driver* p = reinterpret_cast<Device_driver*>(0xffb8);

Serial_port_base *COM1 = Serial_port_base *COM1 = reinterpret_cast<Serial_port_base*>(0x3f8);reinterpret_cast<Serial_port_base*>(0x3f8);

2020Stroustrup/ProgrammingStroustrup/Programming

Page 21: Chapter 25 Embedded systems programming Bjarne Stroustrup

Bit manipulation: Unsigned integersBit manipulation: Unsigned integers

How do you represent a set of bits in C++?How do you represent a set of bits in C++? unsigned char uc;unsigned char uc; // // 8 bits8 bits unsigned short us;unsigned short us; // // typically 16 bitstypically 16 bits unsigned int ui;unsigned int ui; // // typically 16 bits or 32 bitstypically 16 bits or 32 bits

// // (check before using)(check before using)// // many embedded systems have 16-bit many embedded systems have 16-bit

intsints unsigned long int ul;unsigned long int ul; // // typically 32 bits or 64 bitstypically 32 bits or 64 bits

std::vector<bool> vb(93);std::vector<bool> vb(93); // // 93 bits93 bits Use only if you really need more than 32 bitsUse only if you really need more than 32 bits

std::bitset bs(314);std::bitset bs(314); // // 314 bits314 bits Use only if you really need more than 32 bitsUse only if you really need more than 32 bits Typically efficient for multiples of Typically efficient for multiples of sizeof(int)sizeof(int)

2121Stroustrup/ProgrammingStroustrup/Programming

Page 22: Chapter 25 Embedded systems programming Bjarne Stroustrup

Bit manipulationBit manipulation

& & andand | | inclusive orinclusive or ^ ^ exclusive orexclusive or <<<< left shiftleft shift >> right shift >> right shift ~ ~ one’s one’s

complementcomplement

2222

0 1 0 01011 0xaa

0 0 0 11110 0x0f

0 0 0 01010 0x0a

a:

a&b:

b:

0 0 0 11000 0x03b>>2:

1 1 1 00001 0xf0~b:

0 1 0 11111 0xafa|b:

0 1 0 10101 0xa5a^b:

1 0 1 00100 0x54a<<1:

Stroustrup/ProgrammingStroustrup/Programming

Page 23: Chapter 25 Embedded systems programming Bjarne Stroustrup

Bit manipulationBit manipulation Bitwise operationsBitwise operations

& (and)& (and)| | (or)(or)^ ^ (exclusive or – xor)(exclusive or – xor)<< (left shift)<< (left shift)>> (right shift)>> (right shift)~ (one's complement)~ (one's complement)Basically, what the hardware providesBasically, what the hardware provides right:right:

For exampleFor examplevoid f(unsigned short val)void f(unsigned short val) // // assume 16-bit, 2-byte short integerassume 16-bit, 2-byte short integer{{

unsigned char right = val & 0xff ;unsigned char right = val & 0xff ; //// rightmost (least significant) byterightmost (least significant) byteunsigned char left = (val>>8) & 0xff ; unsigned char left = (val>>8) & 0xff ; //// leftmost (most significant) byteleftmost (most significant) bytebool negative = val & 0x8000 ;bool negative = val & 0x8000 ; //// sign bit (if 2’s complement)sign bit (if 2’s complement)//// … …

}}

2323

1 1 00 10 1 0 1 10 0110

Sign bit

1 1 1 111110xff:

8 bits == 1 byte

0

1 0 010

val

0 1 1

falsetrue

Stroustrup/ProgrammingStroustrup/Programming

Page 24: Chapter 25 Embedded systems programming Bjarne Stroustrup

Bit manipulationBit manipulation Or |Or |

Set a bitSet a bit And &And &

Is a bit set? Select (mask) some bitsIs a bit set? Select (mask) some bits For example:For example:

enum Flags { bit4=1<<4, bit3=1<<3, bit2=1<<2, bit1=1<<1, bit0=1 };enum Flags { bit4=1<<4, bit3=1<<3, bit2=1<<2, bit1=1<<1, bit0=1 };unsigned char x = bit3 | bit1;unsigned char x = bit3 | bit1; // // x x becomesbecomes 8+2 8+2x |= bit2;x |= bit2; // // x x becomes becomes 8+4+28+4+2if (x&bit3) {if (x&bit3) { //// is is bit3 bit3 set? (yes, it is)set? (yes, it is)

// // … … }}unsigned char y = x &(bit4|bit2);unsigned char y = x &(bit4|bit2); // // y y becomes becomes 44Flags z = Flags(bit2|bit0); // Flags z = Flags(bit2|bit0); // the cast is necessary because the compilerthe cast is necessary because the compiler

// // doesn’t know thatdoesn’t know that 5 5 is in theis in the Flags Flags rangerange

2424

1 1 1 111110xff:

0 1 111val 0 0 0

Stroustrup/ProgrammingStroustrup/Programming

Page 25: Chapter 25 Embedded systems programming Bjarne Stroustrup

Bit manipulationBit manipulation Exclusive or (xor) ^Exclusive or (xor) ^

a^b means (a|b) & !(a&b) “either a or b but not both”a^b means (a|b) & !(a&b) “either a or b but not both”

unsigned char a = 0xaa;unsigned char a = 0xaa;unsigned char b = 0x0f;unsigned char b = 0x0f;unsigned char c = a^b;unsigned char c = a^b;

Immensely important in graphics and cryptographyImmensely important in graphics and cryptography

2525

0 1 0 01011 0xaa

0 0 0 11110 0x0f

0 1 0 10101 0xa5

a:

a^b:

b:

Stroustrup/ProgrammingStroustrup/Programming

Page 26: Chapter 25 Embedded systems programming Bjarne Stroustrup

Unsigned integersUnsigned integers You can do ordinary arithmetic on unsigned integersYou can do ordinary arithmetic on unsigned integers

Avoid that when you canAvoid that when you can Try never to use unsigned just to get another bit of precisionTry never to use unsigned just to get another bit of precision If you need one extra bit, soon, you’ll need anotherIf you need one extra bit, soon, you’ll need another Don’t mix signed and unsigned in an expressionDon’t mix signed and unsigned in an expression

You can’t completely avoid unsigned arithmeticYou can’t completely avoid unsigned arithmetic Indexing into standard library containers uses unsignedIndexing into standard library containers uses unsigned

(in my opinion, that’s a design error)(in my opinion, that’s a design error)

vector<int> v;vector<int> v;

// …// …

for (int i = 0; i<v.size(); ++i) …for (int i = 0; i<v.size(); ++i) …

for (vector<int>::size_type i = 0; i<v.size(); ++i) …for (vector<int>::size_type i = 0; i<v.size(); ++i) …

for (vector<int>::iterator p = v.begin(); p!=v.end(); ++p) …for (vector<int>::iterator p = v.begin(); p!=v.end(); ++p) …

2626

unsignedcorrect, but pedantic

Yet another way

Stroustrup/ProgrammingStroustrup/Programming

signed

Page 27: Chapter 25 Embedded systems programming Bjarne Stroustrup

ComplexityComplexity

One source of errors is complicated problemsOne source of errors is complicated problems Inherent complexityInherent complexity

Another source of errors is poorly-written codeAnother source of errors is poorly-written code Incidental complexityIncidental complexity

Reasons for unnecessarily complicated codeReasons for unnecessarily complicated code Overly clever programmersOverly clever programmers

Who use features they don’t understandWho use features they don’t understand

Undereducated programmersUndereducated programmers Who don’t use the most appropriate featuresWho don’t use the most appropriate features

Large variations in programming styleLarge variations in programming style

2727Stroustrup/ProgrammingStroustrup/Programming

Page 28: Chapter 25 Embedded systems programming Bjarne Stroustrup

Coding standardsCoding standards A coding standard is a set of rules for what code should A coding standard is a set of rules for what code should

look likelook like Typically specifying naming and indentation rulesTypically specifying naming and indentation rules

E.g., E.g., use “Stroustrup” layoutuse “Stroustrup” layout Typically specifying a subset of a languageTypically specifying a subset of a language

E.g., E.g., don’t use don’t use newnew or or throw throw to avoid predictability problemsto avoid predictability problems Typically specifying rules for commentingTypically specifying rules for commenting

Every function must have a comment explaining what it doesEvery function must have a comment explaining what it does Often requiring the use of certain librariesOften requiring the use of certain libraries

E.g., use E.g., use <iostream> <iostream> rather than rather than <stdio.h> <stdio.h> to avoid safety problemsto avoid safety problems Organizations often try to manage complexity through Organizations often try to manage complexity through

coding standardscoding standards Often they fail and create more complexity than they manageOften they fail and create more complexity than they manage

2828Stroustrup/ProgrammingStroustrup/Programming

Page 29: Chapter 25 Embedded systems programming Bjarne Stroustrup

Coding standardsCoding standards A good coding standard is better than no standardA good coding standard is better than no standard

I wouldn’t start a major (multi-person, multi-year) industrial project without oneI wouldn’t start a major (multi-person, multi-year) industrial project without one A poor coding standard can be worse than no standardA poor coding standard can be worse than no standard

C++ coding standards that restrict programming to something like the C subset C++ coding standards that restrict programming to something like the C subset do harmdo harm

They are not uncommonThey are not uncommon All coding standards are disliked by programmersAll coding standards are disliked by programmers

Even the good onesEven the good ones All programmers want to write their code exactly their own wayAll programmers want to write their code exactly their own way

A good coding standard is prescriptive as well as restrictiveA good coding standard is prescriptive as well as restrictive ““Here is a good way of doing things” as well asHere is a good way of doing things” as well as ““Never do this”Never do this”

A good coding standard gives rationales for its rulesA good coding standard gives rationales for its rules And examplesAnd examples

2929Stroustrup/ProgrammingStroustrup/Programming

Page 30: Chapter 25 Embedded systems programming Bjarne Stroustrup

Coding standardsCoding standards

Common aimsCommon aims ReliabilityReliability PortabilityPortability MaintainabilityMaintainability TestabilityTestability ReusabilityReusability ExtensibilityExtensibility ReadabilityReadability

3030Stroustrup/ProgrammingStroustrup/Programming

Page 31: Chapter 25 Embedded systems programming Bjarne Stroustrup

Some sample rulesSome sample rules No function shall have more than 200 lines (30 would be even No function shall have more than 200 lines (30 would be even

better)better) that is, 200 non-comment source linesthat is, 200 non-comment source lines

Each new statement starts on a new lineEach new statement starts on a new line E.g., E.g., int a = 7; x = a+7; f(x,9);int a = 7; x = a+7; f(x,9); //// violation!violation!

No macros shall be used except for source controlNo macros shall be used except for source control using using #ifdef#ifdef and and #ifndef#ifndef

Identifiers should be given descriptive namesIdentifiers should be given descriptive names May contain common abbreviations and acronymsMay contain common abbreviations and acronyms When used conventionally, When used conventionally, x, y, i, j,x, y, i, j, etc., are descriptive etc., are descriptive Use the Use the number_of_elementsnumber_of_elements style rather than the style rather than the numberOfElementsnumberOfElements style style Type names and constants start with a capital letterType names and constants start with a capital letter

E.g., E.g., Device_driver Device_driver and and Buffer_poolBuffer_pool Identifiers shall not differ only by caseIdentifiers shall not differ only by case

E.g., E.g., HeadHead and and headhead // // violation!violation!

3131Stroustrup/ProgrammingStroustrup/Programming

Page 32: Chapter 25 Embedded systems programming Bjarne Stroustrup

Some more sample rulesSome more sample rules Identifiers in an inner scope should not be identical to identifiers Identifiers in an inner scope should not be identical to identifiers

in an outer scopein an outer scope E.g., E.g., int var = 9; { int var = 7; ++var; }int var = 9; { int var = 7; ++var; } //// violation: violation: varvar hides hides var var

Declarations shall be declared in the smallest possible scopeDeclarations shall be declared in the smallest possible scope Variables shall be initializedVariables shall be initialized

E.g., E.g., int var;int var; //// violation: violation: varvar is not initialized is not initialized Casts should be used only when essentialCasts should be used only when essential Code should not depend on precedence rules below the level of Code should not depend on precedence rules below the level of

arithmetic expressionsarithmetic expressionsE.g., E.g., x = a*b+c;x = a*b+c; // // okokif( a<b || c<=d)if( a<b || c<=d) // // violation: parenthesizeviolation: parenthesize (a<b) (a<b) and and (c<=d)(c<=d)

Increment and decrement operations shall not be used as Increment and decrement operations shall not be used as subexpressionssubexpressions E.g., E.g., int x = v[++i];int x = v[++i]; // // violation (that increment might be overlooked)violation (that increment might be overlooked)

3232Stroustrup/ProgrammingStroustrup/Programming

Page 33: Chapter 25 Embedded systems programming Bjarne Stroustrup

An example of bit manipulationAn example of bit manipulation The Tiny Encryption Algorithm (TEA)The Tiny Encryption Algorithm (TEA)

Originally by David WheelerOriginally by David Wheeler http://143.53.36.235:8080/tea.htmhttp://143.53.36.235:8080/tea.htm

Don’t look too hard at the code (unless you happen to need a Don’t look too hard at the code (unless you happen to need a good simple encryption algorithm for an application); it’s good simple encryption algorithm for an application); it’s simply to give you the flavor of some bit manipulation codesimply to give you the flavor of some bit manipulation code

It takes one word (4 bytes at a time)It takes one word (4 bytes at a time) E.g., E.g., 4 characters from a string or an image file4 characters from a string or an image file

It assumes 4-byte long integersIt assumes 4-byte long integers Explanation is at the link (and in the book)Explanation is at the link (and in the book)

Without the explanation this is just an example of how bit manipulation Without the explanation this is just an example of how bit manipulation code can look. This code is code can look. This code is notnot meant to be self-explanatory. meant to be self-explanatory.

3333Stroustrup/ProgrammingStroustrup/Programming

Page 34: Chapter 25 Embedded systems programming Bjarne Stroustrup

TEATEAvoid encipher(void encipher(

const unsigned long *const v,const unsigned long *const v,unsigned long *const w,unsigned long *const w,const unsigned long * const k)const unsigned long * const k)

{{unsigned long y = v[0];unsigned long y = v[0];unsigned long z = v[1];unsigned long z = v[1];unsigned long sum = 0;unsigned long sum = 0;unsigned long delta = 0x9E3779B9;unsigned long delta = 0x9E3779B9;unsigned long n = 32;unsigned long n = 32;while(n-->0) {while(n-->0) {

y += (z << 4 ^ z >> 5) + z ^ sum + k[sum&3];y += (z << 4 ^ z >> 5) + z ^ sum + k[sum&3];sum += delta;sum += delta;z += (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3];z += (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3];

}}w[0]=y;w[0]=y;w[1]=z;w[1]=z;

}} 3434Stroustrup/ProgrammingStroustrup/Programming

Page 35: Chapter 25 Embedded systems programming Bjarne Stroustrup

TEATEAvoid decipher(void decipher(

const unsigned long *const v,const unsigned long *const v,unsigned long *const w,unsigned long *const w,const unsigned long * const k)const unsigned long * const k)

{ { unsigned long y = v[0];unsigned long y = v[0];unsigned long z = v[1];unsigned long z = v[1];unsigned long sum = 0xC6EF3720;unsigned long sum = 0xC6EF3720;unsigned long delta = 0x9E3779B9;unsigned long delta = 0x9E3779B9;unsigned long n = 32;unsigned long n = 32;// // sum = delta<<5; in general, sum = delta * nsum = delta<<5; in general, sum = delta * nwhile(n-->0) {while(n-->0) {

z -= (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3];z -= (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3];sum -= delta;sum -= delta;y -= (z << 4 ^ z >> 5) + z ^ sum + k[sum&3];y -= (z << 4 ^ z >> 5) + z ^ sum + k[sum&3];

}}w[0]=y;w[0]=y;w[1]=z;w[1]=z;

} } 3535Stroustrup/ProgrammingStroustrup/Programming