How To Write Portable Programs In C



Similar documents
The programming language C. sws1 1

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

The C Programming Language course syllabus associate level

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

DNA Data and Program Representation. Alexandre David

COS 217: Introduction to Programming Systems

Instruction Set Architecture (ISA)

Sources: On the Web: Slides will be available on:

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Chapter 7D The Java Virtual Machine

Informatica e Sistemi in Tempo Reale

CPU Organization and Assembly Language

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Introduction to Virtual Machines

Motorola 8- and 16-bit Embedded Application Binary Interface (M8/16EABI)

CSC 2405: Computer Systems II

EE361: Digital Computer Organization Course Syllabus

Computer Architecture Lecture 2: Instruction Set Principles (Appendix A) Chih Wei Liu 劉 志 尉 National Chiao Tung University

Fast Arithmetic Coding (FastAC) Implementations

Simple Image File Formats

Operating Systems and Networks

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Chapter One Introduction to Programming

sys socketcall: Network systems calls on Linux

1 The Java Virtual Machine

So far we have considered only numeric processing, i.e. processing of numeric data represented

Chapter 3 Operating-System Structures

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Building Applications Using Micro Focus COBOL

OPERATING SYSTEM SERVICES

Outline. hardware components programming environments. installing Python executing Python code. decimal and binary notations running Sage

SmartArrays and Java Frequently Asked Questions

AQA GCSE in Computer Science Computer Science Microsoft IT Academy Mapping

Memory Systems. Static Random Access Memory (SRAM) Cell

1 Abstract Data Types Information Hiding

MatrixSSL Porting Guide

Jonathan Worthington Scarborough Linux User Group

ASSEMBLY PROGRAMMING ON A VIRTUAL COMPUTER

Exceptions in MIPS. know the exception mechanism in MIPS be able to write a simple exception handler for a MIPS machine

Objectives. Chapter 2: Operating-System Structures. Operating System Services (Cont.) Operating System Services. Operating System Services (Cont.

Computer Architecture. Secure communication and encryption.

C++ Programming Language

An Incomplete C++ Primer. University of Wyoming MA 5310

Caml Virtual Machine File & data formats Document version: 1.4

Faculty of Engineering Student Number:

Operating System Overview. Otto J. Anshus

Java Interview Questions and Answers

How to represent characters?

Example of Standard API

Section 1.4. Java s Magic: Bytecode, Java Virtual Machine, JIT,

Lecture 22: C Programming 4 Embedded Systems

Pemrograman Dasar. Basic Elements Of Java

Application Note. Introduction AN2471/D 3/2003. PC Master Software Communication Protocol Specification

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Characteristics of Java (Optional) Y. Daniel Liang Supplement for Introduction to Java Programming

Lecture 7: Programming for the Arduino

B.Sc.(Computer Science) and. B.Sc.(IT) Effective From July 2011

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Chapter 4: Computer Codes

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Variables, Constants, and Data Types

Keil C51 Cross Compiler

COS 318: Operating Systems

System Structures. Services Interface Structure

CS 51 Intro to CS. Art Lee. September 2, 2014

System Calls and Standard I/O

3 SOFTWARE AND PROGRAMMING LANGUAGES

The New IoT Standard: Any App for Any Device Using Any Data Format. Mike Weiner Product Manager, Omega DevCloud KORE Telematics

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Number Representation

Lecture 7: Machine-Level Programming I: Basics Mohamed Zahran (aka Z)

Software: Systems and Application Software

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

Computer Programming I

Management Challenge. Managing Hardware Assets. Central Processing Unit. What is a Computer System?

RTI Monitoring Library Getting Started Guide

Chapter 2 Logic Gates and Introduction to Computer Architecture

Habanero Extreme Scale Software Research Project

Virtual Servers. Virtual machines. Virtualization. Design of IBM s VM. Virtual machine systems can give everyone the OS (and hardware) that they want.

How do Users and Processes interact with the Operating System? Services for Processes. OS Structure with Services. Services for the OS Itself

C Compiler Targeting the Java Virtual Machine

Language Processing Systems

Compilers. Introduction to Compilers. Lecture 1. Spring term. Mick O Donnell: michael.odonnell@uam.es Alfonso Ortega: alfonso.ortega@uam.

Programming languages C

1/20/2016 INTRODUCTION

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

Code Sharing using C++ between Desktop Applications and Real-time Embedded Platforms

ELEC 377. Operating Systems. Week 1 Class 3

CSC230 Getting Starting in C. Tyler Bletsch

RTEMS Porting Guide. On-Line Applications Research Corporation. Edition , for RTEMS July 2015

CS 377: Operating Systems. Outline. A review of what you ve learned, and how it applies to a real operating system. Lecture 25 - Linux Case Study

Operating Systems. Privileged Instructions

Operating System Structures

Transcription:

Writing Portable Programs COS 217 1

Goals of Today s Class Writing portable programs in C Sources of heterogeneity Data types, evaluation order, byte order, char set, Reading period and final exam Important dates Practice exams Lessons from COS 217 Course wrap-up Have a great summer! 2

The Real World is Heterogeneous Multiple kinds of hardware 32-bit Intel Architecture 64-bit IA, PowerPC, Sparc, MIPS, Arms, Multiple operating systems Linux Windows, Mac, Sun, AIX, Multiple character sets ASCII Latin-1, unicode, Multiple byte orderings Little endian Big endian 3

Portability Goal: run program on any other system Do not require any modifications to the program at all Simply recompile the program, and run Program should continue to perform correctly Ideally, the program should perform well, too. Portability is hard to achieve Wide variation in computing platforms Patches and releases are frequent operations Normally, portability is difficult to achieve Still, good to make programs as portable as possible This requires extra care in writing and testing code 4

Programming Language Stick to the standard Program in a high-level language and stay within the language standard However, the standard may be incomplete E.g., char type in C and C++ may be signed or unsigned Program in the mainstream Mainstream implies the established style and use Program enough to know what compilers commonly do Difficult for large languages such as C++ Beware of language trouble spots Some features are intentionally undefined to give compiler implementers flexibility 5

Size of Data Types What are the sizes of char, short, int, long, float and double in C and C++? char has at least 8 bits, short and int at least 16 bits sizeof(char) sizeof(short) sizeof(int) sizeof(long) sizeof(float) sizeof(double) In Java, sizes are defined byte: 8 bits char: 16 bits short: 16 bits int: 32 bits long: 64 bits Our advice: always use sizeof() to be safe 6

Order of Evaluation Order of evaluation may be ambiguous strings[i] = names[++i]; i can be incremented before or after indexing strings! printf( %c %c\n, getchar(), getchar()); The second character in stdin can be printed first! What are the rules in C and C++? Side effects and function calls must be completed at ; && and execute left to right, only as far as necessary What about Java? Expressions including side effects evaluated left to right Our advice: do not depend on the order of evaluation in an expression 7

Characters Signed or Unsigned? Char type may be signed or unsigned Either a 7-bit or an 8-bit character Code that is not portable int i; char s[max+1]; for (i = 0; i < MAX; i++) if ((s[i] = getchar()) == \n ) (s[i] == EOF)) break; s[i] = \0 ; If char is unsigned s[i] is 255, but EOF is -1 Hence, the program will hang! 8

Portable Version Using Integers Solution Use an integer to store the output of getchar() Portable C code int c, i; char s[max+1]; for (i = 0; i < MAX; i++) { if ((c = getchar()) == \n ) (c == EOF)) break; s[i] = c; } s[i] = \0 ; 9

Other C Language Issues Arithmetic or logical shift C: signed quantities with >> may be arithmetic or logical What is -3 >> 1? Does it shift-in a sign bit (i.e., a 1) or a 0? Java: >> for arithmetic right shift, and >>> for logical Byte order Byte order within short, int, and long is not defined 10

Alignment of Structures and Unions Structure consisting of multiple elements struct foo { } char x; int y; Items are laid out in the order of declaration But, the alignment is undefined There might be holes between the elements E.g., y may be 2, 4, or 8 bytes from x 11

Use Standard Libraries Pre-ANSI C may have calls not supported in ANSI C Program will break if you continue use them Header files can pollute the name space Consider the signals defined ANSI C defines 6 signals POSIX defines 19 signals Most UNIX defines 32 or more Take a look at /usr/include/*.h to see the conditional definitions 12

Avoid Conditional Compilation Writing platform-specific code is possible some common code #ifdef MAC #else #ifdef WINDOWSXP #endif #endif But, #ifdef code is difficult to manage Platform-specific code may be all over the place Plus, each part requires separate testing 13

Isolation Common feature may not always work: Life is hard Localize system dependencies in separate files Separate file to wrap the interface calls for each system Example: unix.c, windows.c, mac.c, Hide system dependencies behind interfaces Abstraction can serve as the boundary between portable and non-portable components Java goes one big step further Virtual machine which abstracts the entire machine Independent of operating systems and the hardware 14

Data Exchange Use ASCII text Binary is often not portable Still need to be careful But, even with text, not all systems are the same Windows systems use \r or \n to terminate a line UNIX uses only \n Example Use Microsoft Word and Emacs to edit files CVS assumes all lines have been changed and will merge incorrectly Use standard interfaces which will deal CRLF (carriagereturn and line feed) and newline in a consistent manner 15

Byte Order: Big and Little Endian Example interaction between two machines One process writes a short to outbound socket: unsigned short x; x = 0x1000;... write(sockout, &x, sizeof(x)); Later, another process reads it from inbound socket: unsigned short x;... read(sockin, &x, sizeof(x)); What is the value of x after reading? 16

Byte Order Solutions Fix the byte order for data exchange Sender: unsigned short x; putchar(x >> 8); /* high-order byte */ putchar(x & 0xFF); /* low-order byte */ Receiver: unsigned short x; x = getchar() << 8; /* high-order */ x = getchar() & 0xFF; /* low-order */ Extremely important for network protocols 17

More on Byte Order Language solution Java has a serializable interface that defines how data items are packed C and C++ require programmers to deal with the byte order Binary files vs. text files Binary mode for text files No problem on UNIX Windows will terminate reading once it sees Ctrl-Z as input 18

Internationalization Don t assume ASCII Many countries do not use English Asian languages use 16 bits per character Standardizations Latin-1 arguments ASCII by using all 8 bits Unicode uses 16 bits per character Java uses unicode as its native character set for strings Issues with unicode Byte order issue! Solution: use UTF-8 as an intermediate representation or define the byte order for each character 19

Summary on Portability Language Don t assume char signed or unsigned Always use sizeof() to compute the size of types Don t depend on the order of evaluation of an expression Beware of right shifting a signed value Make sure that the data type is big enough Use standard interfaces Use the common features where possible Provide as much isolation as possible Byte order Fix byte order for data exchange Internationalization Don t assume ASCII and English 20

Important Dates Tuesday May 16 (Dean s Date) Execution Profiler Assignment due Monday, May 22, 9:00-12:00 Frick Chemistry Laboratory 324 Open books, notes, slides, mind, etc. 21

Practice Final Exams Many old exams and answers are online http://www.cs.princeton.edu/courses/archive/spr06/cos2 17/exam2prep We recommend you take some practice exams And then look at the answers afterwards Note that some material differs from term to term Also, ask questions about the practice exams On the listserv To me or Bob Dondero, in person To each other 22

Wrap Up: Goals of COS 217 Understand boundary between code and computer Machine architecture Operating systems Compilers Learn C and the Unix development tools C is widely used for programming low-level systems Unix has a rich development environment Unix is open and well-specified, good for study & research Improve your programming skills More experience in programming Challenging and interesting programming assignments Emphasis on modularity and debugging 23

Relationship to Other Courses Machine architecture Logic design (306) and computer architecture (471) COS 217: assembly language and basic architecture Operating systems Operating systems (318) COS 217: virtual memory, system calls, and signals Compilers Compiling techniques (320) COS 217: compilation process, symbol tables, assembly and machine language Software systems Numerous courses, independent work, etc. COS 217: programming skills, UNIX tools, and ADTs 24

Lessons About Computer Science Modularity Well-defined interfaces between components Allows changing the implementation of one component without changing another The key to managing complexity in large systems Resource sharing Time sharing of the CPU by multiple processes Sharing of the physical memory by multiple processes Indirection Representing address space with virtual memory Manipulating data via pointers (or addresses) 25

Lessons Continued Hierarchy Memory: registers, cache, main memory, disk, tape, Balancing the trade-off between fast/small and slow/big Bits can mean anything Code, addresses, characters, pixels, money, grades, Arithmetic is just a lot of logic operations The meaning of the bits depends entirely on how they are accessed, used, and manipulated Capturing a human s intent is really hard Precise specification of a problem is challenging Correct and efficient implementation of a solution is, too 26

Have a Great Summer! Credit: www.thepbf.com 27