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.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Compilation and Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
Practical techniques & Examples
CSE 303 Lecture 16 Multi-file (larger) programs
Structure of a C program
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
1 CSSE 332 Standard Library, Storage classes, and Make.
. Compilation / Pointers Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
. Plab – Tirgul 3 Makefiles, Memory errors, Variables’ scope.
Using Abstraction to Manage Complexity Abstraction: procedural abstraction & data abstraction. Procedural abstraction=> function development should separate.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Guide To UNIX Using Linux Third Edition
. Memory Management. Memory Organization u During run time, variables can be stored in one of three “pools”  Stack  Static heap  Dynamic heap.
C Programming. C vs C++ C syntax and C++ syntax are the same but... C is not object oriented * There is no string class * There are no stream objects.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Introduction To C++ Programming 1.0 Basic C++ Program Structure 2.0 Program Control 3.0 Array And Structures 4.0 Function 5.0 Pointer 6.0 Secure Programming.
Storage & Linkage: Effects on Scope Rudra Dutta CSC Spring 2007, Section 001.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Modules and Scope Gabriel Hugh Elkaim Spring 2013.
1 Chapter 9 Scope, Lifetime, and More on Functions.
chap13 Chapter 13 Programming in the Large.
Copyright 2001 Oxford Consulting, Ltd1 January Storage Classes, Scope and Linkage Overview Focus is on the structure of a C++ program with –Multiple.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Introduction to Programming Using C Modularity. 2 Contents Modularity Functions Preprocessor Comments Global variables.
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
ECE 103 Engineering Programming Chapter 36 C Storage Classes Herbert G. Mayer, PSU CS Status 8/4/2014 Initial content copied verbatim from ECE 103 material.
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
LECTURE LECTURE 14 Exception Handling Textbook p
+ Storage Classes and Linkage. + Introduction Scope describe the region or regions of a program that can access and identifier Variables can be shared.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
LECTURE 3 Translation. PROCESS MEMORY There are four general areas of memory in a process. The text area contains the instructions for the application.
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.
Functions and Program Structure CSE 2031 Fall June 2016.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Unit 10 Code Reuse. Key Concepts Abstraction Header files Implementation files Storage classes Exit function Conditional compilation Command-line arguments.
Advanced Programming in C
Lecture 3 Translation.
Function: Declaration
C #include <stdio.h> int main() { printf ("hello class\n");
C Functions -Continue…-.
CISC105 – General Computer Science
Linking & Loading.
Storage class in C Topics Automatic variables External variables
CS-3013 Operating Systems C-term 2008
Command-Line Arguments
C Basics.
Instructor: Ioannis A. Vetsikas
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Scope, Parameter Passing, Storage Specifiers
Functions and Program Structure
פרטים נוספים בסילבוס של הקורס
Programming in C Miscellaneous Topics.
Scope Rules and Storage Types
Programming in C Miscellaneous Topics.
10/6: Lecture Topics C Brainteaser More on Procedure Call
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
Compiler vs linker The compiler translates one .c file into a .o file
Variables in C Topics Naming Variables Declaring Variables
The Three Attributes of an Identifier
SPL – PS1 Introduction to C++.
Presentation transcript:

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 and global variables declarations Unresolved references still remain Preprocessor Compiler Square.c Square.o Main.c Main.o

Linking 3 Combines several object files into an executable file No unresolved references Main Preprocessor Compiler Square.c Square.o Main.c Main.o Linker libc.a

The whole process in linux (MSVS is doing the same process): 4 $ 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

Do all files get compiled every time we build the program??? 5 $ 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

Do all files get compiled every time we build the program? – No! 6 Regular projects in Visual studio decide which files need to be compiled and which compiled files can be reused. There are tools to write explicit or implicit buidling rules. For example, the ‘make’ tool which is used often in Linux. The ‘make’ tool uses ‘Makefiles’. Many libraries of code include a Makefile.

Inter module scope rules

Visibility, duration and linkage 8 Translation unit – a “.c” file + its included headers Visibility – the lines in the code where an object (variable, function, typedef) is accessible through a declaration.

Scopes - example 9 int func1( void ); int a = 3; int b = 1; void func2( ) { int a; b = 2;. }

Visibility, duration and linkage 10 Object declaration scope: The maximal region the object can be visible through a declaration. Global declaration – visible throughout the translation unit, starting from the declaration location. Local declarations ( inside {}) – visible in their block (starting from the declaration). Can be hidden by inner scope declarations.

Visibility, duration and linkage 11 Duration: the amount of time, where it is guaranteed that the memory for an object is allocated. Functions - The entire running time of the program. Globals - The entire running time of the program. Locals – Until their scope ends (remember, stack?). Dynamic – Until we free it.

Static variables in a function 12 Keep their value for the next call to the function. That is, globals (duration is the entire program running time) with scope limited to the function. int getUniqueID() { static int id=0; id++; return id; } int main() { int i = getUniqueID(); //i=1 int j = getUniqueID(); //j=2 }

Duration - example 13 int a; // all running time. static int c; // all running time. int func1( void ); // all running time. static void func2() // all running time. { int b; // until func2 ends. static int e; // all running time. }

Visibility, duration and linkage 14 Linkage: The mapping: Name (of variables / functions)  Particular memory address. External linkage: names are associate with the same object throughout the program. All functions and global variables have external linkage (unless declared as static ) Internal linkage: names are associate with the same object in the particular translation unit. All global objects declared as static have internal linkage. No linkage: the object is unique to its scope All locals have no linkage (unless declared with extern, next slide)

extern variables 15 May be defined (defined=compiler allocates memory for it) outside the module file2.c extern int x; // should be imported extern int y; // should be imported int myFunc2() { extern int z; // z from file1.c x = 5; y = 42; } file1.c int x; int y; int z; int myFunc1() { y = 3; }

extern variables 16 May be defined (defined=compiler allocates memory for it) outside the module file2.c extern int x; // should be imported extern int y; // should be imported int myFunc2() { extern int z; // z from file1.c x = 5; y = 42; Considered bad style! } file1.c int x; int y; int z; int myFunc1() { y = 3; }

17 extern variable May be defined (defined=compiler allocates memory for it) outside the module static variable on the global scope Available only in the current module file2.c extern int x; // should be imported extern int y; // should be imported int myFunc2() { extern int z; // z from file1.c x = 5; y = 42; // link error!!! } file1.c int x; static int y; int z; int myFunc1() { y = 3; } extern & static variables

18 Globals: try to avoid!

file.h extern int my_global; 19 file2.c #include “file.h” int myFunc2() { my_global+= 3; } file1.c #include “file.h” // only once, init is good int my_global= 11; static int private_global; myFunc1() { ++my_global; private_global= 33; If you have to use globals, this is the right way

static functions on the global scope: available only in the current module. 20 funcs.h : static void Func1(); void Func2(); main.c: #include "funcs.h" int main() { Func1(); //link error Func2(); }

extern functions? It is the default… 21 funcs.h : // Both are the same extern void Func1(); void Func2(); main.c: #include "funcs.h" int main() { Func1(); Func2(); }

Examples 22 // func1 has external linkage int func1( void ); // func2 has internal linkage // d has no linkage static void func2( int d );

Examples 23 // a has external linkage and // defined=created=memory is allocated) int a; // b has external linkage extern int b; // c has internal linkage and // defined=created=memory is allocated) static int c;

Examples 24 int a; // a has external linkage // and defined=created=memory is allocated extern int b; // b has external linkage static int c; // c has internal linkage and // defined=created=memory is allocated int func1( void ) // func1 has external linkage { int b = 2; // This b has no linkage and // hides the external b declared above static int e; // e has no linkage extern int c; // It is the same as ‘c’ above and // retains internal linkage extern int a; // It is the same as ‘a’ above and // retains external linkage }

Examples 25 int a; // a has external linkage // and defined=created=memory is allocated extern int b; // b has external linkage static int c; // c has internal linkage and // defined=created=memory is allocated int func1( void ) // func1 has external linkage { int b = 2; // This b has no linkage and // hides the external b declared above static int e; // e has no linkage extern int c; // It is the same as ‘c’ above and // retains internal linkage extern int a; // It is the same as ‘a’ above and // retains linkage } extern inside functions is considered bad style!!!

Error handling methods in C

The problem: 27 include void sophisticatedAlgorithm (char* name) { FILE * fd = fopen (name); // using the file // for an algorithm //... } int main() { char name[100]; scanf ("%s", name); sophisticatedAlgorithm (name); //... }

OOP (java / C++) solution: 28 try { FileInputStream fstream = new FileInputStream(name); DataInputStream in = new DataInputStream(fstream); while (in.available() !=0) { System.out.println (in.readLine()); } in.close(); } catch (Exception e) { System.err.println("File input error"); }

How can it be done in C?

Using assert (a short reminder): 30 #include // Sqrt(x) - compute square root of x // Assumption: x non-negative double Sqrt(double x ) { assert( x >= 0 ); // aborts if x < 0 //... } If the program violates the condition, then assertion "x >= 0" failed: file "Sqrt.c", line 7

Using assert: 31 Terminates the program continuation. Good for debugging and logic examination. User can not decide what to do in case of error.

Return values: 32 #include int sophisticatedAlgorithm (char* name) { FILE * fd = fopen (name); // indicate an abnormal termination of // the function if( fd == NULL ) return -1;... // indicate a normal termination of // the function return 0; }

Return values: 33 int main() { int ret = sophisticatedAlgorithm(name); if(ret == -1) { // the exceptional case } else { // the normal case } }

Return values: 34 User can decide what to do in case of error. But: Error handling and legitimate return values are mixed. Requires checking after each function call.

Using global variable – The standard library approach: 35 The idea: Separate between function return code and error description. Sometimes, functions return just 0 in case of success or -1 in case of error or some other binary output. A global variable holds the specific error code (or message) describes the occurred error.

Example: 36 #include // for perror #include #include // for the global variable // errno #include // for strerror const char *FILE_NAME = "/tmp/this_file_does_not_exist.yarly";

Example: 37 int main( int argc, char **argv ) { FILE * fp; fp = fopen( FILE_NAME,”r”); if( fp == NULL) { // Error perror( "Error opening file" ); printf( "Error opening file: %s\n", strerror( errno ) ); } return EXIT_SUCCESS; } Output: Error opening file: No such file or directory

Globals: 38 User can decide what to do in case of error. Error handling and legitimate return values are separated. But, still: Requires checking after each function call.

C exceptions: 39 google: C exceptions will lead to many useful C libraries that implement some kind of exceptions, very similar to java/c++