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

Slides:



Advertisements
Similar presentations
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Advertisements

Compilation and Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
CSE 303 Lecture 16 Multi-file (larger) programs
. Compilation / Pointers Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 17 - The Preprocessor Outline 17.1Introduction 17.2The #include Preprocessor Directive 17.3The.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction.
Guide To UNIX Using Linux Third Edition
 2000 Prentice Hall, Inc. All rights reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction 13.2The #include Preprocessor Directive 13.3The.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 19 - The Preprocessor Outline 19.1 Introduction 19.2 The #include Preprocessor Directive 19.3.
Computer Science 210 Computer Organization Introduction to C.
Programming With C.
History of C 1950 – FORTRAN (Formula Translator) 1959 – COBOL (Common Business Oriented Language) 1971 – Pascal Between Ada.
CMSC 104, Version 9/011 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program 104 C Programming Standards and Indentation.
Algorithms  Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessing Lecture 12 April 7, 2005.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
THE PREPROCESSOR
The Preprocessor Directives Introduction Preprocessing – Occurs before program compiled Inclusion of external files Definition of symbolic constants.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 13 - The Preprocessor Outline 13.1Introduction 13.2The #include Preprocessor Directive 13.3The.
© Oxford University Press All rights reserved. CHAPTER 10 THE PREPROCESSOR DIRECTIVE.
First Compilation Rudra Dutta CSC Spring 2007, Section 001.
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
LECTURE 3 Translation. PROCESS MEMORY There are four general areas of memory in a process. The text area contains the instructions for the application.
Revisiting building. Preprocessing + Compiling 2 Creates an object file for each code file (.c ->.o) Each.o file contains code of the functions and structs.
C++ Functions A bit of review (things we’ve covered so far)
L071 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program Reading Sections
Welcome to C and Computer Structure #include int main() { printf ("hello class\n"); return 0; }
1 Building a program in C: Preprocessor, Compilation and Linkage.
C #include int main() { printf ("hello class\n"); return 0; }
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Programs – Preprocessing, Compilation and Linking
Lecture 3 Translation.
COM S 326X Deep C Programming for the 21st Century Prof. Rozier
Introduction to C Topics Compilation Using the gcc Compiler
13 C Preprocessor.
UMBC CMSC 104 – Section 01, Fall 2016
Week 3-4 Control flow (review) Function definition Program Structures
The Machine Model Memory
Computer Science 210 Computer Organization
C Programming Hardik H. Maheta.
Chapter 13 - The Preprocessor
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Functions Separate Compilation
Introduction to C Topics Compilation Using the gcc Compiler
CSC113: Computer Programming (Theory = 03, Lab = 01)
CS1010 Programming Methodology
Introduction to C Topics Compilation Using the gcc Compiler
C #include <stdio.h> int main() { printf ("hello class\n");
C Basics.
Introduction to C Programming Language
CS1010 Programming Methodology
Pre-processor Directives
User-Defined Functions
Welcome In The World Of ‘C’.  TEXT BOOK: Programming in ANSI ‘C By: E Balagurusamy. TMH  Reference Books: 1) The ‘C Programming Language By: Kernighan.
Computer Science 210 Computer Organization
C Preprocessor(CPP).
Govt. Polytechnic,Dhangar
Programming in C Miscellaneous Topics.
Introduction C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell.
Programming in C Miscellaneous Topics.
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
C Preprocessor Seema Chandak.
C – Programming Language
Programming Languages and Paradigms
An Overview of C.
Compiler vs linker The compiler translates one .c file into a .o file
Introduction to C Topics Compilation Using the gcc Compiler
Executable program (p1)
SPL – PS1 Introduction to C++.
Presentation transcript:

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

History C C++ Java VM Simple to convert to machine code. 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) VM Simple to convert to machine code. Fast and Efficient Secure and Safe Welcome to C Easy to avoid bugs Easy to Debug

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

C – Design Decisions Efficient code (operating systems) “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

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

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

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

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; } ;

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

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 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;

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…

Variables Where to declare? Inside a block (C89 - block beginning) , will be visible only in block. 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! }

Scopes int y=5,x=0; { int x=y; //x is 5 { int y; } } // x is 0 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

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

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

Example – printing powers #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; 20

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() {     } 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;

Building a program in C: Preprocessor, Compilation and Linkage

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

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 Compiler stdio.h tmpXQ.i (C code) hello.o (object file)

Linking Combines object file with external references into an fully executable file, with no unresolved references Main Preprocessor, Compiler Main.c Main.o Linker libc.a Actually a library (.a) is just a collection of object (.o) files chained together to one file. Compiling and linking can be combined into one command (supply the c file as an input, and use –o to specify executable) some libraries are implicitly linked. (libc.a) others (e.g. math = libm.a) – need to use -l<lib name> where in linux the lib prefix and .a suffix can be omitted.

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

The Preprocessor

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

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

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

#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)

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

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 Main Preprocessor Compiler Square.c Square.o Main.c Main.o Linker libc.a

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

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

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

#define – cautions Is it what we intended? #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;

#define – cautions Is it what we intended? #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;

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

#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)

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

#ifndef – for header safety Complex.h: struct Complex { ...      MyStuff.h: #include "Complex.h" Main.c: #include "MyStuff.h" #include "Complex.h" Only one definition is allowed! Error: Complex.h:1: redefinition of `struct Complex'

#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

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

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 Note – in order to be able to compile, the compiler must know about the existence of a function before it is used. It does not need to know the exact implementation - it can leave it as a name, and let the linker insert the actual jump address, but it must know it's declaration.

Debug/Test mode vs Release mode

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; ...

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; ...

#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; ...

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);

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

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 …

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

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

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.

“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 } 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 … }