#include <stdio.h> int main() { printf ("hello class\n"); return 0; }

Similar documents
#include <stdio.h> int main() { printf ("hello class\n"); return 0; }

Reliable C++ development - session 1: From C to C++ (and some C++ features)

Topic 6: A Quick Intro To C

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

C Compilation Model. Comp-206 : Introduction to Software Systems Lecture 9. Alexandre Denault Computer Science McGill University Fall 2006

The C standard library

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

C Programming Review CSC 4320/6320

Compiler Theory. (GCC the GNU Compiler Collection) Sandro Spina 2009

Slide Set 5. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

1 You seek performance 3

Oregon State University School of Electrical Engineering and Computer Science. CS 261 Recitation 2. Spring 2016

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

CS Basics 15) Compiling a C prog.

QUIZ. What is wrong with this code that uses default arguments?

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

INTERMEDIATE SOFTWARE DESIGN SPRING 2011 ACCESS SPECIFIER: SOURCE FILE

just a ((somewhat) safer) dialect.

CS240: Programming in C

QUIZ. What are 3 differences between C and C++ const variables?

The C Preprocessor (and more)!

EL2310 Scientific Programming

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Programming in C. What is C?... What is C?

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

Practical C Issues:! Preprocessor Directives, Multi-file Development, Makefiles. CS449 Fall 2017

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

A software view. Computer Systems. The Compilation system. How it works. 1. Preprocesser. 1. Preprocessor (cpp)

6.s096. Introduction to C and C++

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

EL2310 Scientific Programming

PRINCIPLES OF OPERATING SYSTEMS

Summer May 11, 2010

C: Program Structure. Department of Computer Science College of Engineering Boise State University. September 11, /13

CSE 374 Programming Concepts & Tools. Brandon Myers Winter 2015 C: Linked list, casts, the rest of the preprocessor (Thanks to Hal Perkins)

Advanced Pointer & Data Storage

Have examined process Creating program Have developed program Written in C Source code

Intermediate Programming, Spring 2017*

2 Compiling a C program

Programs. Function main. C Refresher. CSCI 4061 Introduction to Operating Systems

0x0d2C May your signals all trap May your references be bounded All memory aligned Floats to ints round. remember...

CS 113: Introduction to

Lectures 5-6: Introduction to C

Programming. Projects with Multiple Files

G52CPP C++ Programming Lecture 6. Dr Jason Atkin

Page 1. Agenda. Programming Languages. C Compilation Process

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

Intermediate Programming, Spring 2017*

C Introduction. Comparison w/ Java, Memory Model, and Pointers

CMPSC 311- Introduction to Systems Programming Module: Build Processing

Programming in C week 1 meeting Tiina Niklander

High-performance computing and programming I. Introduction to C programming in *NIX

The Make Utility. Independent compilation. Large programs are difficult to maintain. Problem solved by breaking the program into separate files

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

The Make Utility. Independent compilation. Large programs are difficult to maintain. Problem solved by breaking the program into separate files

CMPSC 311- Introduction to Systems Programming Module: Build Processing

Programming in C First meeting

Computer Labs: Debugging

Executables and Linking. CS449 Spring 2016

A Fast Review of C Essentials Part I

Motivation was to facilitate development of systems software, especially OS development.

6.096 Introduction to C++ January (IAP) 2009

CS 61C: Great Ideas in Computer Architecture Introduction to C

Final CSE 131B Spring 2004

COMP322 - Introduction to C++

Contents Lecture 3. C Preprocessor, Chapter 11 Declarations, Chapter 8. Jonas Skeppstedt Lecture / 44

Motivation was to facilitate development of systems software, especially OS development.

Kurt Schmidt. October 30, 2018

PROGRAMMAZIONE I A.A. 2017/2018

Page 1. Stuff. Last Time. Today. Safety-Critical Systems MISRA-C. Terminology. Interrupts Inline assembly Intrinsics

Appendix A. The Preprocessor

What s next. Computer Systems A Programmer s Perspective

Chapter 11 Introduction to Programming in C

Follow us on Twitter for important news and Compiling Programs

High Performance Computing Lecture 1. Matthew Jacob Indian Institute of Science

JTSK Programming in C II C-Lab II. Lecture 3 & 4

The University of Nottingham

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 12, FALL 2012

C introduction: part 1

CS3157: Advanced Programming. Outline

Continue: How do I learn C? C Primer Continued (Makefiles, debugging, and more ) Last Time: A Simple(st) C Program 1-hello-world.c!

Chapter 11 Introduction to Programming in C

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

ELEC 377 C Programming Tutorial. ELEC Operating Systems

CSCI 171 Chapter Outlines

CS201 - Introduction to Programming Glossary By

#include. Practical C Issues: #define. #define Macros. Example. #if

Lectures 5-6: Introduction to C

Functions. Cedric Saule

QUIZ. Source:

Introduction to C CMSC 104 Spring 2014, Section 02, Lecture 6 Jason Tang

Lecture 03 Bits, Bytes and Data Types

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Important From Last Time

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Lecture 3: Instruction Set Architecture

CSc 520 Principles of Programming Languages

Transcription:

C #include <stdio.h> int main() printf ("hello class\n"); return 0;

Working environment Linux, gcc We ll work with c9.io website, which works with ubuntu I recommend to install ubuntu too Also in tirgul 2

History C C++ Java 70 s Development of UNIX. (Richie+Kernigham Bell labs) 80 s Large efficient code. (Stroustrup Bell labs) 90 s Language for the web. (Sun Microsystems) Simple to convert to machine code. VM Fast and Efficient Secure and Safe 3 Welcome to C Easy to avoid bugs Easy to Debug

History C: First "standard" Default int Enums Return struct void // VLA variadic macros inlining multithreading Anonymous structs _Generic K&R 1 st ed. ('78) ANSI C ('89) C99 ('99) C11( 11) This course, without the VLA!

C Design Decisions Bare bones the language leaves maximal flexibility with the programmer Efficient code (operating systems) Full control on memory & CPU usage High-level Type checking High-level constructs Portable Standard language definition Standard library 5

C Warning Signs No run-time checks Array boundary overruns Illegal pointers No memory management Programmer has to manage memory 6

First Program in C // This line is a comment, /* and this line also. */ // This line defines standard I/O library #include <stdio.h> // main program entry point. Start form here int main() // define a block printf("hello class!\n"); return 0; 7

The basic syntax Similar to java you should know it already. 8

Basic Case sensitive White-space not important. End statements with ; Code block defined with and Return value from function using return X; String with " All lines below are legal: int x,y; x=5; x; ; 9

Statements - conditional if (expression) //statement or block else if (expression) //statement or block else (expression) //statement or block switch (integer value) later... 10

Statements - loops The usual suspects: int x,y; //in ANSI C you cannot declare inside the for! for (x=0,y=0;x<10 && y<5;x++,x+=2) //statement or block while (condition) //statement or block 11 do //statement or block while (condition)

Variables Statically typed each variable has a type. Declare by: <type> <name>. int x; int x,y; Optionally initialize (otherwise undefined!) int x=0; 12

Undefined important! int x; Undefined value: as in this example, can have any T (here T=int) value. Undefined behavior: Everything may happen. Probably won t format your disk, but may very well give a hacker a way to do it The biggest problem: often programs seems to work fine although their behavior is undefined, and then 13

Variables Where to declare? 1. Inside a block (C89 - block beginning), will be visible only in block. 2. Outside all blocks global - will be visible everywhere. int x=0; // global int main() int x=1; //local hides global int x=2; //local hides outer scope //x is 2 //x is 1 again! 14

Scopes 15 Code block defined with and. Only declarations inside current or outer scopes are visible. Declarations in inner scope hide declarations in outer scopes: Outmost scope (global) had no brackets. Keep in mind that a function is also a scope. int y=5,x=0; int x=y; //x is 5 int y; // x is 0

Second Program #include <stdio.h> int main() int i; // declares i as an integer int j = 0; // declares j as an integer, // and initializes it to 0 // for( initial ; test condition ; update step ) for( i = 0; i < 10; ++i ) j += i; // shorthand for j = j + i printf("%d %d %d\n", i, j, (i*(i+1))/2); return 0; 16

Running 0 0 0 1 1 1 2 3 3 3 6 6 4 10 10 5 15 15 6 21 21 7 28 28 8 36 36 9 45 45 17

Functions C allows to define functions Syntax: Return type int power( int a, int b ) return 7; Return statement Parameter declaration 18

Procedures Functions that return void void power( int a, int b ) return; Return w/o value (optional) 19

Example printing powers 20 #include <stdio.h> int power( int base, int n ) int i, p; p = 1; for( i = 0; i < n; i++ ) p = p * base; return p; int main() int i; for( i = 0; i < 10; i++ ) printf("%d %d %d\n", i, power(2,i), power(-3,i) ); return 0;

Functions Declaration void funca()... void funcb() funca(); void funcc() funcb(); funca(); funcb(); void funca()... void funcb() funcc(); void funcc() funcb(); Rule 1 : A function knows only functions which were declared above it. Error: funcc is not known yet. 21

Functions Declaration Amendment to Rule 1 : Use forward declarations. void funcc(int param); // or: void funcc(int); void funca() 22 void funcb() funcc(7); void funcc(int param)

Boolean variables non! int main() int a = 5; while(1) if(!(a-3)) printf("** a=3 **\n"); break; printf("a=%d\n",a--); return 0; 23

Building a program in C: Preprocessor, Compilation and Linkage 24

Building a program in C Preprocessor A text processor Commands start with # // copy & paste the file here #include <stdio.h> hello.c Preprocessor tmpxq.i (C code) stdio.h 25

Building a program in C Compiling Takes input C-code and produces machine code (object file) The object file does not contain all external references: It leaves names, such as printf, area, etc. as undefined references hello.c Preprocessor tmpxq.i (C code) Compiler 26 stdio.h hello.o (object file)

Linking Combines object file with external references into an fully executable file, with no unresolved references Main.c Main.o libc.a Main Preprocessor, Compiler Linker 27

Link errors Gcc: /media/sf_biteagle_projects/cbitcoin/test/testc BAddress.c:40: undefined reference to `CBNewByteArrayFromString Visual studio: Error 1 error LNK2019: unresolved external symbol _foo referenced in function _main c:\users\ofirpele\documents\visual studio 2012\Projects\ConsoleApplication5\ConsoleAp plication5\consoleapplication5.obj ConsoleApplication5 28

29 The Preprocessor

Compilation in C hello.c Preprocessor tmpxq.i (C code) Compiler stdio.h hello.o (object file) 30

Preprocessor A single-pass program that: 1. Include header files 2. Expands macros 3. Control conditional compilation 4. Remove comments Outputs a code ready for the compiler to work on. 31

Preprocessor In linux with gcc, we can test what the preprocessor does: > gcc E hello.c will print the C code after running the preprocessing 32

#include directive #include "foo.h" Include the file foo.h, from current directory #include <stdio.h> Include the file stdio.h from the standard library directory (part of compiler installation) 33

Modules & Header files Square.h // interface of function int area... (int x1,int y1, int x2, int y2); Complex.c Main.c #include "Square.h" int main() area (2,3, 5,6); Square.c #include "Square.h" #include <math.h> // implementation int area (int x1,int y1,int x2, int y2)... 34

Do all files get compiled every time we build the program??? $ gcc c Square.c o Square.o $ gcc c Main.c o Main.o $ gcc Square.o Main.o o Main Square.c Main.c Square.o Main.o libc.a Main Preprocessor Compiler Linker 35

Header files Header file contain 1. Definition of data types 2. Declarations of functions & constants 3. That are shared by multiple modules. #include directive allows several modules to share the same set of definitions/declarations 36

#define directive #define FOO 1 int x = FOO; is equivalent to int x = 1; 37

#define with arguments #define SQUARE(x) x*x b = SQUARE (a); is the same as b = a*a; 38

#define cautions #define SQUARE (x) x*x b = SQUARE (a+1); c = SQUARE (a++); Is it what we intended? b = a+1*a+1; //Actually: b = 2*a+1; c = a++*a++; //Actually: c = a*a; a+=2; 39

#define cautions #define SQUARE (x) ((x)*(x)) b = SQUARE (a+1); c = SQUARE (a++); Is it what we intended? b = ((a+1)*((a+1)); //Now ok c = ((a++)*(a++)); //Did not help: c = a*a; a+=2; 40

#define #define directive should be used with caution! Alternative to macros: Constants enum FOO = 1 ; or const int FOO = 1; Functions inline functions (C99,C++) 41

#define Multi-line: All preprocessor directive effect one line (not c statement). To insert a line-break, use \ : BAD: #define x (5 + 5) // x == 10! GOOD: #define x (5 + \ 5) // x == 10! 42

#if directive Allows to have conditional compilation #if defined(debug) // compiled only when DEBUG exists printf("x = %d\n", X); #endif 43

#ifndef for header safety Complex.h: struct Complex... MyStuff.h: #include "Complex.h" Main.c: #include "MyStuff.h" #include "Complex.h" Error: Complex.h:1: redefinition of `struct Complex' 44

#ifndef header safety Complex.h (revised): #ifndef COMPLEX_H #define COMPLEX_H struct Complex... #endif Main.c: #include "MyStuff.h" #include "Complex.h" // no error this time 45

#pragma once header safety Complex.h (revised): #pragma once struct Complex... Main.c: #include "MyStuff.h" #include "Complex.h" // no error this time 46

Preprocessor summary Text processing program. Does not know c rules Operates before compilation, output passed to compiler. Can do copy and paste / cut #include paste the included file here Commonly included file (.h by convention) contains forward declarations #define copy the macro body, paste it where macro name appears - constants, simple "functions" #if condition not fulfilled, cut the code - Conditional compilation e.g. debugging code 47

Debug/Test mode vs Release mode 48

Debug/Test mode vs Release mode #include <assert.h> #define MAX_INTS 100 int main() int ints[max_ints]; // i should be in bounds, but is it really? i = foo(<something complicated>); // safety assertions assert(i>=0); assert(i<max_ints); ints[i] = 0;... 49

Debug/Test mode vs Release mode #include <assert.h> #define MAX_INTS 100 int main() int ints[max_ints]; // i should be in bounds, but is it really? i = foo(<something complicated>); // safety assertions assert(i>=0); assert(i<max_ints); ints[i] = 0;... 50

#define NDEBUG #include <assert.h> #define MAX_INTS 100 int main() int ints[max_ints]; // i should be in bounds, but is it really? i = foo(<something complicated>); // safety assertions assert(i>=0); assert(i<max_ints); ints[i] = 0;... 51

assert // bad, foo() will not be called // if the compiler removes the assert() // if NDEBUG is defined assert(foo() == 0); // good int errcode = foo(); assert(errcode == 0); 52

assert Use for: Catching bugs Don't use for: checking malloc, user input,... 53

assert.h #include <assert.h> // Sqrt(x) - compute square root of x // Assumption: x non-negative double sqrt(double x ) assert( x >= 0 ); // aborts if x < 0 54

assert.h // procedure that actually prints error message void assert(char* file,int line,char* test); #ifdef NDEBUG #define assert(e) ((void)0) #else #define assert(e) \ ((e)? (void)0 : \ assert( FILE, LINE, #e)) #endif 55

assert.h Important coding practice Declare implicit assumptions Sanity checks in code Check for violations during debugging/testing 56

57 Compilation

Compilation Translate the c code to machine code. Every machine architecture has a different code. Need separate compilation. x86 : older but still common PCs 32-bit (Intel/AMD) x64 : newer PCs 64-bit (Intel/AMD) ARM : (many versions) Phones, tablets (ARM) Translated code is an executable the OS can load it to the machine memory, and the let the CPU do whatever you wrote in the code. 58

Assembly int y=2; int mult(int x) return x*y; mov eax,dword ptr [x] imul eax,dword ptr [1177000h] int main() return mult(5); push 5 call 11711A4h 59 Only part of the assembly code is shown here. Actually each command has binary code, and the sequence of these code is the object file.

Compiling warnings

Compiling warnings Add -Wall flag to catch things like this: if (i=3) //bug, we meant i==3 61