How to learn C? CSCI [4 6]730: A C Refresher or Introduction. Diving In: A Simple C Program 1-hello-word.c

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

CMPT 300. Operating Systems. Brief Intro to UNIX and C

2 Compiling a C program

EL2310 Scientific Programming

CS240: Programming in C

EL2310 Scientific Programming

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

Makefiles SE 2XA3. Term I, 2018/19

Problem Set 1: Unix Commands 1

Reviewing gcc, make, gdb, and Linux Editors 1

Laboratory 1 Semester 1 11/12

Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3

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

PRINCIPLES OF OPERATING SYSTEMS

Software Development With Emacs: The Edit-Compile-Debug Cycle

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

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

Lecture 3. Introduction to Unix Systems Programming: Unix File I/O System Calls

Introduction to Supercomputing

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview

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

How Compiling and Compilers Work

C / C++ Coding Rules

Programming in C week 1 meeting Tiina Niklander

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

Executables and Linking. CS449 Spring 2016

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

Exercise 1: Basic Tools

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

CS Basics 15) Compiling a C prog.

Programming in C First meeting

Introduction to the C-Language and Programming Environment

GDB and Makefile. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

CSE 124 Discussion (10/3) C/C++ Basics

Programming in C First meeting Tiina Niklander

Saint Louis University. Intro to Linux and C. CSCI 2400/ ECE 3217: Computer Architecture. Instructors: David Ferry

Chapter 2. Basics of Program Writing

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

Sep 12, 2006 Lecture 2: System Programming

COSC350 System Software

CSE 351. GDB Introduction

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

introduction week 1 Ritsumeikan University College of Information Science and Engineering Ian Piumarta 1 / 20 imperative programming about the course

Unix and C Program Development SEEM

UNIX Makefile. C Project Library Distribution and Installation.

CSCI 2132 Final Exam Solutions

Multiple file project management & Makefile

Review of Scientific Programming in C and Fortran. Michael McLennan Software Architect HUBzero Platform for Scientific Collaboration

independent compilation and Make

Lecture 03 Bits, Bytes and Data Types

CS240: Programming in C. Lecture 2: Overview

{C} Tools of the Trade

Programming in C in a UNIX environment

CSE 303 Lecture 8. Intro to C programming

Obtained the source code to gcc, one can just follow the instructions given in the INSTALL file for GCC.

COSC345 Software Engineering. Make

Systems Programming. Fatih Kesgin &Yusuf Yaslan Istanbul Technical University Computer Engineering Department 18/10/2005

Laboratorio di Tecnologie dell'informazione

ENERGY 211 / CME 211. Evolution

Beyond this course. Machine code. Readings: CP:AMA 2.1, 15.4

CSE 351. Introduction & Course Tools

INTERMEDIATE SOFTWARE DESIGN SPRING 2011 ACCESS SPECIFIER: SOURCE FILE

Oregon State University School of Electrical Engineering and Computer Science. CS 261 Recitation 1. Spring 2011

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

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

ECE 471 Embedded Systems Lecture 4

Lab 1: First Steps in C++ - Eclipse

The CS-220 Development Environment

CS354 gdb Tutorial Written by Chris Feilbach

Debugging. ICS312 Machine-Level and Systems Programming. Henri Casanova

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

Basic Compilation Control with Make

HPC User Environment

CS480. Compilers Eclipse, SVN, Makefile examples

CS631 - Advanced Programming in the UNIX Environment. UNIX development tools

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

CSSE 332 Standard Library, Storage classes, and Make

Tutorial 1 C Tutorial: Pointers, Strings, Exec

Advanced School in High Performance and GRID Computing November 2008

CS 300 Leftovers. CS460 Pacific University 1

CAAM 420 Daily Note. Scriber: Qijia Jiang. Date: Oct.16. Project 3 Due Wed 23.Oct. Two parts: debug code and library exercise.

by Pearson Education, Inc. All Rights Reserved.

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

Section 1: Tools. Kaifei Chen, Luca Zuccarini. January 23, Make Motivation How... 2

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

System Programming. Introduction to Unix

Programming in C S c o t t S c h r e m m e r

Computers and Computation. The Modern Computer. The Operating System. The Operating System

Errors During Compilation and Execution Background Information

The Linux Programming Environment. Computer Science Department Texas State University

CS201 - Lecture 1 The C Programming Language

Intermediate Programming, Spring 2017*

1 You seek performance 3

CAAM 420 Fall 2012 Lecture 15. Roman Schutski

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

Computer Programming. The greatest gift you can give another is the purity of your attention. Richard Moss

Creating a Shell or Command Interperter Program CSCI411 Lab

CpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input

We first learn one useful option of gcc. Copy the following C source file to your

Transcription:

How to learn C? CSCI [4 6]730: A C Refresher or Introduction Hello Word! ~/ctutorial/ In addition to syntax you need to learn: the Tools. the Libraries. And the Documentation (how to access) Practice on cluster nodes on nike.» vcf0 vcf5 on nike.cs.uga.edu {vcf5:maria:85} ssh vcf4.cs.uga.edu Are you sure you want to continue connecting (yes/no)? Yes maria@vcf4.cs.uga.edu's password: Maria Hybinette, UGA 1 Maria Hybinette, UGA 2 Diving In: A Simple C Program 1-hello-word.c Diving In: A Simple C Program 1-hello-word.c /* header files go up here -- specifies headers needed for routines */ /* note that C comments are enclosed within a slash and a star, and may wrap over lines */ // but if you use the latest gcc, two slashes to end of line will // work too, like C++ /* header files go up here -- specifies headers needed for routines */ /* note that C comments are enclosed within a slash and a star, and may wrap over lines */ // but if you use the latest gcc, two slashes will work too, like C++ // a comment about comments single line doesn t always work /* multiline comment should work everywhere */ /* main returns an integer */ int main( int argc, char *argv[] ) { printf( hello, world\n ); return(0); /* returns 0 by conventions indicates all went well */ } Maria Hybinette, UGA 3 /* main returns an integer */ int main( int argc, char *argv[] ) { /* printf is our output function; by default it writes to standard out */ /* printf returns an integer, but we ignore it here */ /*1 [stout] >& redirect stout and stderr */ /* >& /dev/null - suppress all output */ /*(cat f1 > myout) >& myerror */ printf( hello, world\n ); /* return 0 by conventions indicates all went well */ return(0); } Maria Hybinette, UGA 4

*.c File Name How to Compile and Run a C-program: 1-hello-world.c Naming the program (e.g., 1-hello-world.c, main.c )» Arbitrary Not Like in Java where file name is connected with file content (class name).» Constraint: Need to end with a *.c Coming up: compiling (4.9.0)» /usr/bin/gcc» gcc v Maria Hybinette, UGA 5 C-code gcc 1-hello-world.c gcc starts the compile process 1. Executes cpp (processes # directives) Creates source code (default path where to look: /usr/ include). Expands the code. 2. Compilation (cc1): gcc -print-prog-name=cc1 Transforms C code to assembly code (.s code) 3. Assembler (as) runs Transforms assembly code to machine code 4. Linker (ld) runs./a.out cpp expanded cc1 Assembly as C -Code Code Links code together to create the final executable 1 argv[1]=null (end)» int main( int argc, char *argv[] ) Machine Code Machine Code Maria Hybinette, UGA 6 ld Compile Command line & flags cpp 1-hello-world.c > 1-hello-world.cpp cc1 1-hello-world.cpp» Creates: 1-hello-world.s as -o 1-hello-world.o 1-hello-world.s ld tricky to use for linking.» gcc 1-hello-world.o -o 1-hello-world» ld 1-hello-world.o -lc entry main -I /lib/ld-linux.so.2 prompt> gcc -o first first.c # -o lets you specify the executable name prompt> gcc -Wall first.c # -Wall gives much better warnings prompt> gcc g first.c # use -g to enable debugging with gdb prompt> gcc -O first.c # use -O to turn on optimization strip. Maria Hybinette, UGA 7 find. -name first-print Maria Hybinette, UGA 8

Linking Libraries Lets say that again. Example: fork() requires a library, namely the C- library. The C library is automatically linked, so all we need then is :» The including the right #include file <>, -i, -I to to find the prototype of the function (return type, date types of parameters).» How to find out: man fork //[unistd.h]» CAVEAT: the controversial and dreaded LD_LIBRARY_PATH» (C11)» May fix (e.g., readline) problems fork() requires the C-library (clib). The C library is automatically linked in, so all we need then is :» How do you know what to include?» man fork» BUT Wait a minute why a library - Fork is a system call! [a request of service by the OS from the application] C library provides C wrappers for all system calls which simply traps into the OS The real system call in Linux e.g., is sys_fork() Maria Hybinette, UGA 9 Maria Hybinette, UGA 10 Other Libraries: The Math Library (e.g., sqrt(), pow()) gcc [ flag... ] file... -lm [ library... ] #include <math.h>» In /usr/lib» Statically linked.a (compile time) Combines code (copies) directly into executable» Dynamically linked shared library.so (run time) Smaller code base (can be shared by multiple processes) A reference and only links when needed, smaller code base (some work), hooks in code triggers the run time system to load in the library, only when needed» /usr/libm.a & /usr/libm.so (different location per installation)» Link editor searches for library in a certain order.» -Im directory path include) and L(directory path) Maria Hybinette, UGA 11 Multiple Files (hw.c, helper.c Makefile2) prompt> gcc o hw hw.c helper.c -lm Problem: Remake everything (2 programs here) every time, even if the change is only in hw.c Approach: Separate 2 step compilation process that only re-compiles source files that have been modified Create object files then link *.o files Then link these files into an executable Maria Hybinette, UGA 12

Separate Compilation Make & Makefiles # note that we are using -Wall for warnings and -O for optimization prompt> gcc -Wall -O -c hw.c prompt> gcc -Wall -O -c helper.c prompt> gcc -o hw hw.o helper.o -lm -c flag produces an object file Machine level code (not executable) Need to link to make an executable prompt> gcc -o hw hw.c helper.c -lm Maria Hybinette, UGA 13 Make make things easier to handle the compilation process. target: prerequisite1 prerequisite2 command1 command2 Target usually the name of executable of 1) the program file (e.g., helloworld) or 2) the action (e.g., clean). command1/command2 preceeded by a tab \t Maria Hybinette, UGA 14 Make Makefiles (be aware of the dreaded white space phenomena) What is going on here? hw: hw.o helper.o gcc -o hw hw.o helper.o -lm hw.o: hw.c gcc -O -Wall -c hw.c helper.o: helper.c gcc -O -Wall -c helper.c clean: rm -f hw.o helper.o hw vi enables you to see white spaces by ( escape then) :list or :set list Maria Hybinette, UGA 15 hw: hw.o helper.o gcc -o hw hw.o helper.o -lm hw.o: hw.c gcc -O -Wall -c hw.c helper.o: helper.c gcc -O -Wall -c helper.c clean: rm -f hw.o helper.o hw Goes to target hw (first target) need the prerequisites Check them in turn (according to times stamp) and see if they need to be re-made Maria Hybinette, UGA 16

Make macros Advice Getting Started with Makefile Make facilitates macros (short cuts):» CC = gcc» OBJECTS = data.o main.o» Project1: $(OBJECTS) Examples of Special macros» CC, CFLAGS (compiler, and compiler flags)» $@ short cut for full name of current target Start by using a working Makefile (a template), then edit the file how you like it. Be aware of white spaces Be aware of white spaces Be aware of white spaces %.o : %.c $(CC) c o $@ $(CFLAGS) Maria Hybinette, UGA 17 Maria Hybinette, UGA 18 Debugger Debugger The debugger: it is another program Gnu Debugger (GDB) gcc g o program program.c» -g make the executable debuggable -g ing gcc.» Symbol Table List of names of identifier is accessible to the debugger type, scope, and location of identifiers (e.g., variables and functions)» Prevent the compiler from re-arranging (optimizing) the code Maria Hybinette, UGA 19 Visualization Maria Hybinette, UGA 20

UNIX Tools: Examining Obj Files Debugging nm - list symbols from object file» http://linux.about.com/library/cmd/blcmdl1_nm.htm» nm a symboltable objdump more detailed information» objdump syms program readelf anoher aproaach #include <stdio.h> struct Data { int x; }; int main( int argc, char *argv[] ) { struct Data *p = NULL; printf("%d\n", p->x); } Maria Hybinette, UGA 21 Maria Hybinette, UGA 22 Debugging gcc g -o 3-buggy 3-buggy.c {nike:maria:428} 3-buggy Segmentation Fault(coredump) gdb 3-buggy» run» print p» break main https://www.gnu.org/software/gdb/ documentation/ http://sourceware.org/gdb/current/ onlinedocs/gdb.html Maria Hybinette, UGA 23 gdb debug a running program {vcf5:maria:5} 4-longprogram & {vcf5:maria:5} ps f grep maria maria 3520 3497 0 10:06 pts/1 00:00:00 4-longprogram maria 3521 3497 5 10:07 pts/1 00:00:00 ps ef {vcf5:maria:7} gdb 4-longprogram 3520 (gdb) list (gdb) next Single stepping until exit from function nanosleep_nocancel, 3 for (i=0; i < 10000; i++) (gdb) print i $1 = 34 (gdb) next 15 a = a+i; \(gdb) print i $2 = 36 (gdb) kill Kill the program being debugged? (y or n) y (gdb) Maria Hybinette, UGA 24

GDB A Note : Integrated Development Environments (IDE) (gdb) help Help running Help files Help breakpoints Debugger, Editor, Compilation Eclipse - http://www.eclipse.org/callisto/c-dev.php Microsoft Visual Studios Run, step, next Maria Hybinette, UGA 25 Maria Hybinette, UGA 26 Documentation: Oh Man The Ultimate C Reference Guides man XXX man -k Maria Hybinette, UGA 27 The C book or the K & R Book :» The C Programming Language, by Brian Kernighan and Dennis Ritchie (thin, concise and all you really need ) The GDB Booklet» Debugging with GDB: The GNU Source-Level Debugger, by Richard M. Stallman, Roland H. Pesch http://sourceware.org/gdb/current/ onlinedocs/gdb.html The Unix System Programming Book» Advanced Programming in the UNIX Environment, by W. Richard Stevens» There is a later edition Maria Hybinette, UGA 28