PROGRAMMAZIONE I A.A. 2017/2018

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

Unit 4 Preprocessor Directives

A Fast Review of C Essentials Part II

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

PROGRAMMAZIONE I A.A. 2017/2018

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

Errors During Compilation and Execution Background Information

CSE 410: Systems Programming

The Compilation Process

CMPSC 311- Introduction to Systems Programming Module: Debugging

Essentials for Scientific Computing: Source Code, Compilation and Libraries Day 8

Program Translation. text. text. binary. binary. C program (p1.c) Compiler (gcc -S) Asm code (p1.s) Assembler (gcc or as) Object code (p1.

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

1 A Brief Introduction To GDB

CMPSC 311- Introduction to Systems Programming Module: Debugging

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

COMsW Introduction to Computer Programming in C

PROGRAMMAZIONE I A.A. 2017/2018

Chapter 7: Preprocessing Directives

mp2 Warmup Instructions (Updated 1/25/2016 by Ron Cheung for using VMs)

CS/COE 0449 term 2174 Lab 5: gdb

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

C and Programming Basics

Binghamton University. CS-220 Spring C Debugging Basics. No relevant text

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

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Draft. Chapter 1 Program Structure. 1.1 Introduction. 1.2 The 0s and the 1s. 1.3 Bits and Bytes. 1.4 Representation of Numbers in Memory

SOFTWARE ARCHITECTURE 5. COMPILER

OBJECT ORIENTED PROGRAMMING USING C++

The Compilation Process

C and C++ 2. Functions Preprocessor. Alan Mycroft

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

Programming Tips for CS758/858

Intermediate Programming, Spring 2017*

12. Debugging. Overview. COMP1917: Computing 1. Developing Programs. The Programming Cycle. Programming cycle. Do-it-yourself debugging

Program Design: Using the Debugger

CMPSC 311- Introduction to Systems Programming Module: Build Processing

Simple C Program. Assembly Ouput. Using GCC to produce Assembly. Assembly produced by GCC is easy to recognize:

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.

Basic functions of a debugger

CMPSC 311- Introduction to Systems Programming Module: Build Processing

Modifiers. int foo(int x) { static int y=0; /* value of y is saved */ y = x + y + 7; /* across invocations of foo */ return y; }

C Preprocessor. Prabhat Kumar Padhy

Control flow and string example. C and C++ Functions. Function type-system nasties. 2. Functions Preprocessor. Alastair R. Beresford.

MODULE 5: Pointers, Preprocessor Directives and Data Structures

Programming for Engineers C Preprocessor

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

3 PREPROCESSOR. Overview. Listing 3-0. Table 3-0.

1. A student is testing an implementation of a C function; when compiled with gcc, the following x86-64 assembly code is produced:

Compilation, Disassembly, and Profiling (in Linux)

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

PROGRAMMAZIONE I A.A. 2017/2018

CS2141 Software Development using C/C++ Compiling a C++ Program

Follow us on Twitter for important news and Compiling Programs

C for Engineers and Scientists: An Interpretive Approach. Chapter 7: Preprocessing Directives

The C Pre Processor ECE2893. Lecture 18. ECE2893 The C Pre Processor Spring / 10

Lecture 2. Xiaoguang Wang. January 16th, 2014 STAT 598W. (STAT 598W) Lecture 2 1 / 41

MPATE-GE 2618: C Programming for Music Technology. Unit 4.1

GDB Linux GNU Linux Distribution. gdb gcc g++ -g gdb EB_01.cpp

Chapter 2 A Quick Tour

Credits and Disclaimers

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #54. Organizing Code in multiple files

Conditional Compilation

PROGRAMMAZIONE I A.A. 2017/2018

Short Notes of CS201

UNIX Makefile. C Project Library Distribution and Installation.

Debugging and Debugger. Terminology. GNU gcc and gdb. Debugging C programs in Unix and Windows Environments - Part One

GDB 1 GDB 2 GDB. Fortran Pascal GDB 4. hoge.c. Fig. 1. calc.c. Fig GDB. GDB Debian. # apt-get install gdb

Tutorial No. 2 - Solution (Overview of C)

CS201 - Introduction to Programming Glossary By

ECE/ME/EMA/CS 759 High Performance Computing for Engineering Applications

Outline. Compiling process Linking libraries Common compiling op2ons Automa2ng the process

Lab 10: Introduction to x86 Assembly

Programming Studio #9 ECE 190

CSCI 171 Chapter Outlines

INTERMEDIATE SOFTWARE DESIGN SPRING 2011 ACCESS SPECIFIER: SOURCE FILE

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 7

Separate Compilation of Multi-File Programs

CS165 Computer Security. Understanding low-level program execution Oct 1 st, 2015

Scientific Programming in C IX. Debugging


PROGRAMMAZIONE I A.A. 2017/2018

Appendix A. The Preprocessor

make and makefile CS 211

Lecture 03 Bits, Bytes and Data Types

Using the Debugger. Michael Jantz Dr. Prasad Kulkarni

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14

Binghamton University. CS-220 Spring X86 Debug. Computer Systems Section 3.11

Macros in C/C++ Computer Science and Engineering College of Engineering The Ohio State University. Lecture 33


Come and join us at WebLyceum

This course has three parts. Elements of C programming. Arithmatic and Error analysis. Some algorithms and their implementation

CSE 351. GDB Introduction

CSE 374 Programming Concepts & Tools

Credits and Disclaimers

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

Language Translation. Compilation vs. interpretation. Compilation diagram. Step 1: compile. Step 2: run. compiler. Compiled program. program.

CS354 gdb Tutorial Written by Chris Feilbach

Compiling and Linking

Compiler Design IIIT Kalyani, West Bengal 1. Introduction. Goutam Biswas. Lect 1

Transcription:

PROGRAMMAZIONE I A.A. 2017/2018

STEPS OF GCC

STEPS file.c Preprocessor Compiler file1.o file2.o Assembler Linker executable file

PREPROCESSOR

PREPROCESSOR The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs. The C preprocessor provides four separate facilities that you can use as you see fit: Inclusion of header files. These are files of declarations that can be substituted into your program. Macro expansion. You can define macros, which are abbreviations for arbitrary fragments of C code, and then the C preprocessor will replace the macros with their definitions throughout the program. Conditional compilation. Using special preprocessing directives, you can include or exclude parts of the program according to various conditions.

INCLUDE An #include directive instructs the preprocessor to insert the contents of a specified file in the place of the directive. ü#include <filename> ü #include "filename" Use the first form, with angle brackets, when you include standard library header ü#include <math.h> // Prototypes of mathematical functions, // with related types and macros. Use the second form, with double quotation marks, to include source files specific to your programs. ü#include "myproject.h"

WHERE TO FIND HEADER FILES For files specified between angle brackets (<filename>), the preprocessor usually searches in certain system directories, such as /usr/local/include and /usr/include on Unix systems, for example. For files specified in quotation marks ("filename"), the preprocessor usually looks in the current directory first, which is typically the directory containing the program s other source files. If such a file is not found in the current directory, the preprocessor searches the system include directories as well. A filename may contain a directory path. If so, the preprocessor looks for the file only in the specified directory.

DEFINING AND USING MACROS You can define macros in C using the preprocessor directive #define. A common use of macros is to define a name for a numeric constant: ü#define ARRAY_SIZE 100 double data[array_size]; ARRAY_SIZE is replaced with 100 The preprocessor expands the macro; that is, it replaces the macro name with the text it has been defined to represent

USING MACROS WITH MACROS No macro can be expanded recursively #define PI 3.141593 #define A (A / 8)

UNDEF You cannot use a second #define directive to redefine an identifier that is currently defined as a macro, unless the new replacement text is identical to the existing macro definition. #include<stdlib.h> #define FILE_SIZE 42 #define FILE_SIZE 42 #define FILE_SIZE 50 #define FILE_SIZE 42 #undef FILE_SIZE #define FILE_SIZE 50 void swap (int* a, int* b) { /*. */ } #undef FILE_SIZE #define FILE_SIZE 50 int abs (int a) { /*. */ }

CONDITIONAL COMPILING Conditional expressions at compile time. #include<stdio.h> #define NUM 10 int main(void) { #if(num == 0) printf("\nnumber is Zero"); #elif(num > 0) printf("\nnumber is Positive"); #else printf("\nnumber is Negative"); #endif } int main(void) { printf("\nnumber is Positive"); }

CONDITIONAL COMPILING You can also test whether a given macro is defined using the #ifdef and #ifndef directives. Their syntax is: ü#ifdef identifier ü#ifndef identifier #ifndef MESSAGE #define MESSAGE "You wish! #endif

PREPROCESSING Before submitting the source code to the actual compiler, the preprocessor remove comments, executes directives and expands macros in the source files. GCC ordinarily leaves no intermediate output file containing the results of this preprocessing stage. However, you can save the preprocessor output for diagnostic purposes by using the -E option, which directs GCC to stop after preprocessing. The preprocessor output is directed to the standard output stream, unless you indicate an output filename using the -o option: ügcc -E -o mylibrary.i mylibrary.c

INCLUDE OPTIONS -Idirectory[:directory[... ]] gcc -c -I/Users/francescosantini/Desktop/ mylibrary.c gcc -c -I/Users/francescosantini/Desktop/ - I/Users/francescosantini/Desktop/ProgrammI/exercises mylibrary.c When header files are required by #include directives in the source code, search for them in the specified directory (or directories), in addition to the system s standard include directories.

-D NAME -D name: defines the symbol name before preprocessing the source files. The macro name must not be defined in the source and header files themselves. Use this option together with #ifdef name directives in the source code for conditional compiling. // myfile.c #include <stdio.h> void main() { #ifdef DEBUG printf("debug run\n"); #else printf("release run\n"); #endif } $ gcc -D DEBUG myfile.c -o myfile $./myfile Debug run $ gcc myfile.c -o myfile $./myfile Release run

COMPILER

ASSEMBLY At the heart of the compiler s job is the translation of C programs into the machine s assembly language. Assembly language is a human-readable programming language that correlates closely to the actual machine code. Consequently, there is a different assembly language for each CPU architecture. Ordinarily GCC stores its assembly-language output in temporary files, and deletes them immediately after the assembler has run.

-S You can use the -S option to stop the compiling process after the assembly-language output has been generated. If you do not specify an output filename, GCC with the -S option creates an assembly-language file with a name ending in.s for each input file compiled. gcc -S mylibrary.c The compiler preprocesses mylibrary.c and translates it into assembly language, and saves the results in the file mylibrary.s.

EXAMPLE int main() { int a= 5; a++; }.section TEXT, text,regular,pure_instructions.macosx_version_min 10, 11.globl _main.align 4, 0x90 _main: ## @main.cfi_startproc ## BB#0: pushq %rbp Ltmp0:.cfi_def_cfa_offset 16 Ltmp1:.cfi_offset %rbp, -16 movq %rsp, %rbp Ltmp2:.cfi_def_cfa_register %rbp xorl %eax, %eax movl $5, -4(%rbp) movl -4(%rbp), %ecx addl $1, %ecx movl %ecx, -4(%rbp) popq %rbp retq.cfi_endproc.subsections_via_symbols

ASSEMBLER

ASSEMBLER Because each machine architecture has its own assembly language, GCC invokes an assembler on the host system to translate the assembly-language program into executable binary code. The result is an object file, which contains the machine code to perform the functions defined in the corresponding source file, and also contains a symbol table describing all objects in the file that have external linkage.

COMPILING AND LINKING SEPARAT. If you invoke GCC to compile and link a program in one command, then its object files are only temporary, and are deleted after the linker has run. Most often, however, compiling and linking are done separately. The -c option instructs GCC not to link the program, but to produce an object file with the filename ending.o for each input file: $ gcc c mylibrary.c

LINKING

LINKING The linker joins a number of binary object files into a single executable file. In the process, it has to complete the external references among your program s various modules by substituting the final locations of the objects for the symbolic references. The linker does this using the same information that the assembler provides in the symbol table. Furthermore, the linker must also add the code for any C standard library functions you have used in your program.

STEPS file.c Preprocessor file.i Compiler file1.o file2.o Assembler file.s file.o Linker executable file

GDB

GDB If the GNU C compiler, GCC, is available on your system, then GDB is probably already installed as well. ügdb -version GNU gdb (GDB) 7.10 Copyright (C) 2015 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-apple-darwin15.0.0". Type "show configuration" for configuration details. For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word".

SYMBOLS GDB is a symbolic command line debugger. Symbolic here means that you can refer to variables and functions in the running program by the names you have given them in your C source code. In order to display and interpret these names, the debugger requires information about the types of the variables and functions in the program, and about which instructions in the executable file correspond to which lines in the source files. a symbol table, which the compiler and linker include in the executable file when you run GCC with the -g option: ügcc g -o test test.c

EXAMPLE #include<stdio.h> test.c int main() { int a[]= {6,5,4,3,2}; for (int i= 0; i < sizeof(a) / sizeof(int); i++) { if(a[i] > a[i+1]) continue; puts("errore"); break; } return 0; } MacBook-Francesco:ProgrammI francescosantini$ gcc -g -o test test.c MacBook-Francesco:ProgrammI francescosantini$./test Errore

EXAMPLE You can start by entering the command list, or just its initial l for short, to list a few lines of source code of the program you are debugging. MacBook-Francesco:ProgrammI francescosantini$ gdb test 10 lines by default, l again (gdb) l 1 #include<stdio.h> 2 3 int main() 4 { 5 int a[]= {6,5,4,3,2}; 6 7 for (int i= 0; i < sizeof(a) / sizeof(int); i++) { 8 9 if(a[i] < a[i+1]) 10 continue; (gdb)

HOW TO WORK WITH IT Before you instruct GDB to run the program, you should tell it where you want it to stop. You can do this by setting a breakpoint. When the debugger reaches the breakpoint, it interrupts the execution of your program, giving you an opportunity to examine the program s state at that point. Furthermore, once the program has been interrupted at a breakpoint, you can continue execution line by line, observing the state of program objects as you go. To set a breakpoint, enter the command break, or b for short. Breakpoints are usually set at a specific line of source code or at the beginning of a function.

EXAMPLE (gdb) l 1 #include<stdio.h> 2 3 int main() 4 { 5 int a[]= {6,5,4,3,2}; 6 7 for (int i= 0; i < sizeof(a) / sizeof(int); i++) { 8 9 if(a[i] > a[i+1]) 10 continue; (gdb) b 7 Breakpoint 1 at 0x100000ecc: file test.c, line 7. (gdb) r Starting program: /Users/francescosantini/Desktop/ProgrammI/test Breakpoint 1, main () at test.c:7 7 for (int i= 0; i < sizeof(a) / sizeof(int); i++) {

EXAMPLE Upon reaching the breakpoint, the debugger interrupts the execution of the program and displays the line containing the next statement to be executed. For this purpose, GDB provides the commands next, or n, and step, or s. The next and step commands behave differently if the next line to be executed contains a function call. The next command executes the next line, including all function calls, and interrupts the program again at the following line. The step command, on the other hand, executes a jump to the function called in the line, and interrupts the program again at the first statement in the function body.

PRINT VARIABLES At this point we can check to see whether the values of the variables are correct. We can do this using the print command (p for short), which displays the value of a given expression: $number is a GDB variable that the debugger creates. (gdb) s 9 if(a[i] > a[i+1]) (gdb) p a[i] $1 = 6 (gdb) p a[i+1] $2 = 5 (gdb) p a[i+2] $3 = 4

EXAMPLE Breakpoint 1, main () at test.c:7 7 for (int i= 0; i < sizeof(a)/ sizeof(int); i++) { (gdb) n 9 if(a[i] > a[i+1]) (gdb) n 10 continue; (gdb) n 7 for (int i= 0; i < sizeof(a)/ sizeof(int); i++) { (gdb) n 9 if(a[i] > a[i+1]) (gdb) n 10 continue; (gdb) n 7 for (int i= 0; i < sizeof(a)/ sizeof(int); i++) { (gdb) n 9 if(a[i] > a[i+1]) (gdb) n 10 continue; (gdb) n 7 for (int i= 0; i < sizeof(a)/ sizeof(int); i++) { (gdb) n 9 if(a[i] > a[i+1]) (gdb) n 10 continue;

EXAMPLE (gdb) n 7 for (int i= 0; i < sizeof(a) / sizeof(int); i++) { (gdb) n 9 if(a[i] > a[i+1]) (gdb) n 12 puts("errore"); (gdb) p a[i] $2 = 2 (gdb) p a[i+1] $3 = 32767 (gdb) p i int a[]= {6,5,4,3,2} $4 = 4 6 5 4 3 2 32767

LAST COMMANDS The command continue, abbreviated c, lets program execution continue until it reaches the next breakpoint or the end of the program. To stop gdb, enter the command quit or q. info breakpoints, delete breakpoints (gdb) info breakpoints Num Type Disp Enb Address What 1 breakpoint keep y 0x0000000100000f01 in main at test.c:10 breakpoint already hit 3 times (gdb) d 1 (gdb) c Continuing. Errore