C Essentials. C Essentials - Training Course
|
|
- Regina Shelton
- 6 years ago
- Views:
Transcription
1 C Essentials C Essentials - Training Course
2 Day 1 Morning 1. Introduction Source File Header File Object File Declaration and Definition Preprocessing, Compiling, Linking, Loading and Running Executable file format Segments (.bss,.code,.data etc) Creating static library Creating dynamic library Discussion on where c fits 2. Data type, operator and expression Data types and sizes - Integer - Floating point type - Pointer - Array - Enum Constant Variable Declaration and Definition Operator - Assignment operator and expression - Arithmetic operator - Relational operator - Conditional operator Bit wise operator Type conversion Conditional expression Day 1 Afternoon 3. Array Pointers References Defining and initializing Array. Defining and initializing Pointers. Using pointers to access array elements. Pointers and const qualifiers. Dynamically allocated arrays. Multidimensional array argument to function
3 Day 2 Morning 4. Control Structure Statement and Block Statements - If - Switch - While - For - do while Break and Continue Goto and Labels 5. Complex Data Types struct - Structures and functions - Array of structure - Self referential structure - Typedef - Unions - Bit-fields Arrays Pointers Ampersand operator(&) Day 2 Afternoon 6. Function Scope rule Header rule Block structure Function declaration and Definition Value and reference Parameters Inline function Recursion Preprocessor - File inclusion - Macro - Conditional inclusion
4 Day 3 Morning 7. Input and Output Standard Input and Output Buffered i/o Variable length argument list File access Line input and output Error handling - stderr and exit 8. Storage class specifier Automatic Const Global Extern Register Static Volatile Day 3 Afternoon 9. Misc Debugging with gdb 64 bit data i/o
5 DISCLAIMER This document is edited on Cent OS 5 using Open Office Draw Package. CentOS is freely download from centos.org/download Open Office can be obtained through yum or through openoffice.org Text of this document is written in Bembo Std Otf(13 pt) font. Code parts are written in Consolas (10 pts) font. This training material is provided through Minh, Inc, B'lore, India Document is available at minhinc.com/training/advance-c-slides.pdf For suggestion(s) or complaint(s) write to us at training@minhinc.com Document modified on 12/2016 Document contains 71 pages.
6 Day 1 1. Introduction Source File Header File Object File Declaration and Definition Pre-processing, Compiling, Linking, Loading and Running Executable file format Segments (.bss,.code,.data etc) Creating static library Creating dynamic library Discussion on where c fits Stages of Program Development v Architecture design v > Detailed design v Redefine design > Edit source files ^ v Compile source file v Link Object files v Test and debug executable program Function consists of header and body - Header contains preprocessor statements and class declarations (except template inclusion case where source is also included) - Body, enclosed in {brackets contains statements, each terminated by semicolon One function must be one called main() - C start up code calls main function as the entry point in the program. Global variables are initialized prior the entry to main function. Program execution starts in main, and progresses, statement by statement, until the last statement in main is completed Definition of variable class and functions put in source file.
7 A source file contains definition of variable and functions. <<source.c>> extern int i; // declaration int func(); // declaration int i=10;//declaration and definition int func(){//definition Compiling one source file needs only declarations of the variable and the function be visible. Definition is not required while generating object file. $ cat source.c #include <stdio.h> int func(); int main(){ func(); return 0; $ g++ -c source.c -o source.o <-- compiling without definition $ nm source.o U _Z4funcv <--- U is undefined U gxx_personality_v T main 1. Introduction Source File Header File Object File Declaration and Definition Pre-processing, Compiling, Linking, Loading and Running Executable file format Segments (.bss,.code,.data etc) Creating static library Creating dynamic library Discussion on where c fits Header contains constants, macros, system wide global variables, preprocessor statements and declarations. Header file is included with #include example. $ cat header.h #ifndef HEADER_H #define HEADER_H #include <stdio.h> const int i=10; extern int j; struct A{ ; void put_s(const char*); #endif
8 $cat source1.c #include "header.h" void put_s(const char *cp){ printf("puts %s\n",cp); $cat source2.c #include "header.h" int j=15; $cat main.c #include "header.h" int main(int argc, char *argv[]){ puts("hello world"); printf("j %d\n",j); return 0; $ g++ source1.c source2.c main.c -o headersource $./headersource hello world j Introduction Source File Header File Object File Declaration and Definition Pre-processing, Compiling, Linking, Loading and Running Executable file format Segments (.bss,.code,.data etc) Creating static library Creating dynamic library Discussion on where c fits A file that contains compiled code is known as an object file. Compiler creates object file which is binary file. It is of three types a) Relocatable file This type of object file contains data and code that can be linked together with other relocatable files to produce an executable binary or a shared object file. It is similar as the.o file produced when we compile a code the following way :
9 $gcc -Wall -c test.c -o test.o So the test.o produced after the operation above would be a relocatable file. $ nm mathoperation.o T add T div U fixit <-- Undefined T mul $ objdump -x mathoperation.o mathoperation.o: file format elf64-x86-64 mathoperation.o architecture: i386:x86-64, flags 0x : HAS_RELOC, HAS_SYMS start address 0x Sections: Idx Name Size VMA LMA File off Algn 0.text a **2 CONTENTS, ALLOC, LOAD, RELOC, READONLY, CODE 1.data c 2**2 CONTENTS, ALLOC, LOAD, DATA 2.bss c 2**2 ALLOC 3.comment e c 2**0 CONTENTS, READONLY 4.note.GNU-stack ca 2**0 CONTENTS, READONLY 5.eh_frame d0 2**3 CONTENTS, ALLOC, LOAD, RELOC, READONLY, DATA SYMBOL TABLE: l df *ABS* mathoperation.c l d.text text l d.data data l d.bss bss l d.note.gnu-stack note.GNU-stack l d.eh_frame eh_frame l d.comment comment g F.text add g F.text mul g F.text div *UND* fixit RELOCATION RECORDS FOR [.text]: OFFSET TYPE VALUE d R_X86_64_PC32 fixit-0x RELOCATION RECORDS FOR [.eh_frame]: OFFSET TYPE VALUE R_X86_64_PC32.text R_X86_64_PC32.text+0x R_X86_64_PC32.text+0x
10 $ cat mathoperation.c void fixit(int,int); int add(int a,int b){ return a+b; int mul(int a,int b){ return a*b; int div(int a,int b){ if (b=0)fixit(a,b); return a/b; b) Shared object file This type of object file is used by the dynamic linker to combine it with the executable and/or other shared object. It is similar as the.so file produced when the code is compiled with the -fpic (position independent code) flag in the following way : $gcc -c -Wall -Werror -fpic shared.c -o shared.o $gcc -shared -o libshared.so shared.o A shared object file libshared.so is produced as output. example. $gcc -c -fpic mathoperation.c -o mathoperation.o $ nm mathoperation.o T add T div U fixit U _GLOBAL_OFFSET_TABLE_ <- relocating table T mul $ gcc -c -fpic mathoperation.c -o mathoperation.o $ gcc -shared -o libmathoperation.so mathoperation.o $ ldd libmathoperation.so linux-vdso.so.1 => (0x00007fffbd5fe000) libc.so.6 => /lib64/libc.so.6 (0x00007ffd916b4000) /lib64/ld-linux-x86-64.so.2 (0x00007ffd91c8b000)
11 $ nm libmathoperation.so T add B bss_start b completed.6333 w cxa_finalize@@glibc_ t deregister_tm_clones f T div t do_global_dtors_aux e00 t do_global_dtors_aux_fini_array_entry e10 d dso_handle e18 d _DYNAMIC D _edata B _end T _fini < Undefined U fixit d0 t frame_dummy df8 t frame_dummy_init_array_entry r FRAME_END d _GLOBAL_OFFSET_TABLE_ w gmon_start b8 T _init w _ITM_deregisterTMCloneTable w _ITM_registerTMCloneTable e08 d JCR_END e08 d JCR_LIST w _Jv_RegisterClasses c T mul t register_tm_clones d TMC_END c) Executable file This type of object file is a file that is capable of executing a program when run. $ gcc -Wall test.c -o test Tool - objdump, nm Example <<main.c>> #include "sample.h" int main(int argc, char *argv[]){ struct fraction frtn; frtn.numerator=12; frtn.denominator=5; func(&frtn); return 0;
12 <<sample.c>> #include <stdio.h> #include "sample.h" void func(struct fraction *f){ printf("value %d\n",f->numerator/f->denominator); <<sample.h>> #ifndef SAMPLE_H #define SAMPLE_H struct fraction { int numerator; int denominator; ; void func(struct fraction *f); #endif $ objdump -r sample.o sample.o: file format pe-i386 RELOCATION RECORDS FOR [.text]: OFFSET TYPE VALUE b dir32.rdata DISP32 _printf RELOCATION RECORDS FOR [.eh_frame]: OFFSET TYPE VALUE DISP32.text $ nm sample.o b.bss d.data r.eh_frame r.rdata r.rdata$zzz t.text T _func U _printf $ ldd a.out linux-vdso.so.1 => (0x00007fffffbfe000) libc.so.6 => /lib64/libc.so.6 (0x00007f96f51ee000) /lib64/ld-linux-x86-64.so.2 (0x00007f96f55c3000)
13 1. Introduction Source File Header File Object File Declaration and Definition Pre-processing, Compiling, Linking, Loading and Running Executable file format Segments (.bss,.code,.data etc) Creating static library Creating dynamic library Discussion on where c fits Declaration - Asserts the existence of a variable, function or type defined elsewhere in the program. A variable may be declared by preceding its type with the keyword extern. int a; // just declaration void func();//just declaration c++ int a // declaration and definition extern a // declaration - Declaration can be made multiple times. Definition - Allocates storage for a variable of a specified type and optionally initializes the variable. int a=10; //declaration and definition void func(){// declaration and definition - Definition must be only once. - How are declarations written so that variables are properly declared during compilation? - How are declarations arranged so that all the pieces will be properly connected when the program is loaded? - How are declarations organized so there is only one copy? - How are external variables initialized?
14 1. Introduction Source File Header File Object File Declaration and Definition Pre-processing, Compiling, Linking, Loading and Running Executable file format Segments (.bss,.code,.data etc) Creating static library Creating dynamic library Discussion on where c fits source file source file source file source file v v v v object file object file object file object file v v..< >. link. < Runtime Library v Executable Code Preprocessor - It is a program that runs as part of compilation of a c program. It is not part of compiler. In simplistic terms, a C Preprocessor is just a text substitution tool and they instruct compiler to do required preprocessing before actual compilation. All preprocessor commands begin with a pound symbol (#). It must be the first non blank character, and for readability, a preprocessor directive should begin in first column. Following section lists down all important preprocessor directives: Directive #define #include #undef #ifdef #ifndef #if #else #elif #endif #error #pragma Description Substitutes a preprocessor macro Inserts a particular header from another file Undefines a preprocessor macro Returns true if this macro is defined Returns true if this macro is not defined Tests if a compile time condition is true The alternative for #if #else an #if in one statement Ends preprocessor conditional Prints error message on stderr Issues special commands to the compiler, using a standardized method
15 Tool - cpp $ cat test.h #ifndef TEST_H #define TEST_H int func(): #endif $ cat test.cpp #include "test.h" int main(){ return 0; $ cpp test.cpp # 1 "test.cpp" # 1 "<command-line>" # 1 "/usr/include/stdc-predef.h" # 1 "<command-line>" 2 # 1 "test.cpp" # 1 "test.h" 1 int func(): # 2 "test.cpp" 2 int main(){ return 0; Compiling Source Files Once your program is written in C, it is ready to be translated into a machine-readable language. A compiler translates C statements into machine statements - A compiler creates object code, which is an intermediary step between source code and final executable code - The compiler checks for syntax errors; e.g., Missing punctuation - The compiler performs simple optimization on your code; e.g., eliminate a redundant statement Tool gcc Linking Object Files - The linker links together all object modules to form an executable image of the program - The output of the linker is an executable image, which can be loaded into memory and executed - The linker resolves any references to library functions - If your program uses a library routine, like sqrt, the linker finds the object code corresponding to this routine and links it within the final executable image - The linker is automatically invoked by the compiler
16 Loading Your Program The loader loads your program into the computer's memory On most systems, this is performed automatically by the operating system when you run the program Most embedded systems require you to explicitly run a loader program to get the program into memory Tool - gcc 1. Introduction Source File Header File Object File Declaration and Definition Preprocessing, Compiling, Linking, Loading and Running Executable file format Segments (.bss,.code,.data etc) Creating static library Creating dynamic library Discussion on where c fits Executable file format which once loaded by a suitable executable loader, can be directly Executed by the CPU rather than become interpreted by software. In addition to the binary application code, the executable may contain headers and tales with relocation and fix up information as well as various kinds of meta data. ELF(Executable and Linkable File Format) - unix/linux COFF(Command Object File Format) - windows PE windows MZ DOS Mach-O (mac OS and ios) ELF Header #define EI_NIDENT 16 typedef struct { e_ident[ei_nident]; unsigned char e_type; Elf32_Half e_machine; Elf32_Half e_version; Elf32_Word e_entry; Elf32_Addr e_phoff; Elf32_Off e_shoff; Elf32_Off e_flags; Elf32_Word e_ehsize; Elf32_Half e_phentsize; Elf32_Half e_phnum; Elf32_Half e_shentsize; Elf32_Half e_shnum; Elf32_Half e_shstrndx; Elf32_Ehdr;
17 1. e_ident In order to support all this the initial information in ELF file contains information on how to interpret the file independent of the processor on which the executable is running. Name Value Purpose EI_MAG 0 File identification EI_MAG1 1 File identification EI_MAG2 2 File identification EI_MAG3 3 File identification EI_CLASS 4 File class EI_DATA 5 Data encoding EI_VERSION 6 File version EI_PAD 7 Start of padding bytes EI_NIDENT 16 Size of e_ident[] EI_MAG The first four bytes above hold the magic number 0x7fELF EI_CLASS An ELF can have two classes, 32 bit or 64 bit. This makes the file format portable. EI_DATA This member gives the information on data encoding, big endian or little endian format. EI_VERSION This member provides information on object file version. EI_PAD This member marks the start of unused bytes in the e_indent array of information. EI_NIDENT This member provides the size of array e_indent. This helps in parsing the ELF file. 2. e_type This member identifies the type of object file. For example, an object file can be of following types : Name Value Meaning ET_NONE 0 No file type ET_REL 1 Relocatable file ET_EXEC 2 Executable file ET_DYN 3 Shared object file ET_CORE 4 Core file NOTE: The above list is not exhaustive but still gives information on main object file types that ELF can refer to. 3. e_machine This member gives information on architecture that an ELF file requires. Name Value Meaning ET_NONE 0 No machine EM_M32 1 AT&T WE EM_SPARC 2 SPARC EM_386 3 Intel Architecture EM_68K 4 Motorola EM_88K 5 Motorola EM_860 7 Intel EM_MIPS 8 MIPS RS3000 Big-Endian EM_MIPS_RS4_BE 10 MIPS RS4000 Big-Endian RESERVED Reserved for future use 4. Additional Members Apart from the above three members, it also has the following members: e_version: Provides the ELF object file version information. e_entry: Provides the virtual address information of the entry point to which the system must transfer the control so that the process can be initiated. e_phoff: Holds the offset to program header table. This information is stored in terms of bytes. In absence of a program header table, the information contained by this member is zero. e_shoff: Holds the offset to section header table. As with e_phoff, this information too is stored in form of bytes and in absence of a section header table, the information contained by this field is zero. e_flags: Holds information related to process specific flags. e_ehsize: Holds information related to ELF header size in byes. e_phentsize: Holds information related to size of one entry in the object file s program header table. Note that all the entries are same in size. e_phnum: Holds the information related to number of entries in program header table. e_shentsize: Holds the information related to size of one entry in the section header table. The size is represented in form of number of bytes. e_shnum: Gives the information related to the number of entries in the section header table.
18 Tool - readelf used to list the object data main() { printf("hello World\n"); $ readelf -h hello.o ELF Header: Magic: 7f 45 4c Class: ELF64 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: REL (Relocatable file) Machine: Advanced Micro Devices X86-64 Version: 0x1 Entry point address: 0x0 Start of program headers: 0 (bytes into file) Start of section headers: 312 (bytes into file) Flags: 0x0 Size of this header: 64 (bytes) Size of program headers: 0 (bytes) Number of program headers: 0 Size of section headers: 64 (bytes) Number of section headers: 13 Section header string table index: 10 $ readelf -S hello.o There are 13 section headers, starting at offset 0x138: Section Headers: [Nr] Name Type Address Offset Size EntSize Flags Link Info Align [ 0] NULL [ 1].text PROGBITS AX [ 2].rela.text RELA [ 3].data PROGBITS WA [ 4].bss NOBITS WA [ 5].rodata PROGBITS c A [ 6].comment PROGBITS e MS [ 7].note.GNU-stack PROGBITS [ 8].eh_frame PROGBITS A [ 9].rela.eh_frame RELA c [10].shstrtab STRTAB d [11].symtab SYMTAB [12].strtab STRTAB
19 The readelf program is capable of performing disassembly: $ readelf -i 1 hello.o 0x pushl %ebp 0x movl %esp,%ebp 0x pushl $0x0 0x call 0x x d addl $4,%esp 0x movl %ebp,%esp 0x popl %ebp 0x ret The.rel.text section contains the re-locations for the.text section of the file, and we can display them as follows: $ readelf -r hello.o Relocation section data:.rel.text (0x2 entries) Tag: Value R_386_32 (0 ) Tag: Value 00b02 R_386_PC32 (0 printf) $ readelf -l hello Elf file type is EXEC (Executable file) Entry point 0x There are 9 program headers, starting at offset 64 Program Headers: Type Offset VirtAddr PhysAddr FileSiz MemSiz Flags Align PHDR 0x x x x f8 0x f8 R E 8 INTERP 0x x x x c 0x c R 1 [Requesting program interpreter: /lib64/ld-linux-x86-64.so.2] LOAD 0x x x x x R E LOAD 0x e10 0x e10 0x e10 0x x RW DYNAMIC 0x e28 0x e28 0x e28 0x d0 0x d0 RW 8 NOTE 0x x x x x R 4 GNU_EH_FRAME 0x ec 0x ec 0x ec 0x x R 4 GNU_STACK 0x x x x x RW 10 GNU_RELRO 0x e10 0x e10 0x e10 0x f0 0x f0 R 1 Section to Segment mapping: Segment Sections interp 02.interp.note.ABI-tag.note.gnu.build-id.gnu.hash.dynsym.dynstr.gnu.version.gnu.version_r.rela.dyn.rela.plt.init.plt.text.fini.rodata.eh_frame_hdr.eh_frame 03.init_array.fini_array.jcr.dynamic.got.got.plt.data.bss 04.dynamic 05.note.ABI-tag.note.gnu.build-id 06.eh_frame_hdr init_array.fini_array.jcr.dynamic.got
20 1. Introduction Source File Header File Object File Declaration and Definition Preprocessing, Compiling, Linking, Loading and Running Executable file format Segments (.bss,.code,.data etc) Creating static library Creating dynamic library Discussion on where c fits Unix/Linux process virtual address space high address \ command line arguments / and environment stack v ^ heap uninitialized data \ initialized to (bss) / zero by exec \ initialized data \ read from program line text / by exec low address / When an executable program is read into system memory by the kernel and executed, it becomes a process. We can consider system memory to be divided into two distinct regions. One is user space, and the other is kernel Space. Every process has is own user space (about 2GB virtual space,32bit) and are prevented from interfering with one another. The mode change which is from user mode to kernel mode is called a context switch.
21 Kernel Space < context switching User Space < Text, Data and Stack. The user process is divided into three segments or regions, they are: text, data and stack. Text Segment. The Text segment (a.k.a the Instruction segment) contains the executable program code and constant data. The text segment is marked by the operating system as read- only and can not be modified by the process. Multiple processes can share the same text segment. Processes share the text segment if a second copy of the program is to be executed concurrently. Sharing can be turned off by using the -N option on the compile time. Data Segment. The data segment, which is contiguous (in a virtual sense) with the text segment, can be subdivided into initialized data (e.g. in C/C++, variables that are declared as static or are static by virtual of their placement) and uninitialized (or 0-initialized data. The uninitialized data area is also called BSS (Block Started By Symbol). Heap Segment During its execution lifetime, a process may request additional data segment space. Library memory allocation routines (e.g., new, malloc, calloc, etc.) in turn make use of the system calls brk and sbrk to extend the size of the data segment. The newly allocated space is added to the end of the current uninitialized data area. This area of available memory is also called "heap".
22 Stack Segment. The stack segment is used by the process for the storage of automatic identifier, register variables, and function call information. The stack grows towards the uninitialized data segment. The u area. In addition to the text, data, and stack segment, the OS also maintains for each process a region called the u area (User Area). The u area contains information specific to the process (e.g. open files, current directory, signal action, accounting information) and a system stack segment for process use. If the process makes a system call (e.g., the system call to write in the function in main ), the stack frame information for the system is stored in the system stack segment. Again, this information is kept by the OS in an area that the process doesn't normally have access to. Thus, if this information is needed, the process must use special system call to access it. Like the process itself, the contents of the u area for the process are paged in and out bye the OS. Process Memory Addresses. The system keep s track of the virtual addresses associated with each user process segment. This addresses information is available to the process and can be obtained by referencing the external variables etext, edata, and end. The addresses (not the contents) of these three variable correspond respectively to the first valid address above the text, initialized data, and uninitialized data segments. #include <iostream> extern int etext, edata, end; using namespace std; int main( ){ cout << "Adr etext: " << hex << &etext << "\t "; cout << "Adr edata: " << hex << &edata << "\t "; cout << "Adr end: " << hex << &end << "\n"; char *s1 = "hello"; //in initialized data segmenta static int a=1; //in initialized data segment static int b; //in uninitialized data segment char s2[] = "hello"; //in the stack area. int * c = new int; cout <<hex << s1 << endl; cout <<hex << &a << endl; cout <<hex << &b << endl; cout <<hex << s2 << endl; cout <<hex << c << endl; delete c; return 0;
23 $g++ add.cpp $./a.out Adr etext: 0x400e4d Adr edata: 0x Adr end: 0x6021c0 hello 0x60208c 0x6021b8 hello 0X23ce Introduction Source File Header File Object File Declaration and Definition Preprocessing, Compiling, Linking, Loading and Running Executable file format Segments (.bss,.code,.data etc) Creating static library Creating dynamic library Discussion on where c fits A static library is set of object files that were copied into a single file. The static file is created with the archiver (ar). <<calc_mean.c>> //#include <stdio.h> double mean(double a, double b) { return (a+b) / 2; <<calc_mean.h>> double mean(double, double); Creating the static library First, calc_mean.c is turned into an object file: $gcc -c calc_mean.c -o calc_mean.o Then, the archiver (ar) is invoked to produce a static library (named libmean.a) out of the object file calc_mean.o. $ar rcs libmean.a calc_mean.o Note: the library must start with the three letters lib and have the suffix.a.
24 $cat calc.c #include <stdio.h> #include "calc_mean.h" int main(){ printf ("mean of 3, 6 is %f \n",mean(3,6)); return 0; $ gcc -c calc_mean.c -o calc_mean.o $ ar cr libmean.a calc_mean.o $ gcc -c calc.c -o calc.o $ gcc -o calc calc.o -L. -lmean $./calc mean of 3, 6 is $ gcc -o calc -L. -lmean calc.o calc.o: In function `main': calc.c:(.text+0x2f): undefined reference to `mean' collect2: error: ld returned 1 exit status $ nm libmean.a calc_mean.o: T mean 1. Introduction Source File Header File Object File Declaration and Definition Preprocessing, Compiling, Linking, Loading and Running Executable file format Segments (.bss,.code,.data etc) Creating static library Creating dynamic library Discussion on where c fits Shared library (also known as a shared object, or as a dynamically linked library) is similar to a archive in that it is a grouping of object files. When a shared library is linked into a program, the final executable does not actually contain the code that is present in the shared library. Instead, the executable merely contains a reference to the shared library.
25 The program using the library <<main.c>> #include <stdio.h> #include "calc_mean.h" int main(){ printf ("mean of 3, 6 is %f \n",mean(3,6)); return 0; $ gcc -c -fpic calc_mean.c -o calc_mean.o $ gcc -c calc.c -o calc.o $ gcc -shared -fpic -o libmean.so calc_mean.o $ ldd libmean.so linux-vdso.so.1 => (0x00007fffadffe000) libc.so.6 => /lib64/libc.so.6 (0x00007f546f7ed000) /lib64/ld-linux-x86-64.so.2 (0x00007f546fdc4000) $ gcc -o calc calc.o -L. -lmean $ ldd calc linux-vdso.so.1 => (0x00007fffa58de000) libmean.so => not found libc.so.6 => /lib64/libc.so.6 (0x00007f4e10d70000) /lib64/ld-linux-x86-64.so.2 (0x00007f4e ) $ export LD_LIBRARY_PATH=. $./calc mean of 3, 6 is In order to avoid LD_LIBRARY_PATH programmer can add -Wl,rpath,<lib path> to the command link line $ pwd /home/sc $ echo $LD_LIBRARY_PATH $ rm calc $ gcc -o calc calc.o -L. -lmean -Wl,-rpath=/home/sc/ $./calc mean of 3, 6 is $ gcc -o calc calc.o -L. -lmean $./calc./calc: error while loading shared libraries: libmean.so: cannot open shared object file: No such file or directory
26 1. Introduction Source File Header File Object File Declaration and Definition Preprocessing, Compiling, Linking, Loading and Running Executable file format Segments (.bss,.code,.data etc) Creating static library Creating dynamic library Discussion on where c fits C's type system and error checks exist only at compile-time. The compiled code runs in a stripped down run-time model with no safety checks for bad type casts,bad array indices, or bad pointers. There is no garbage collector to manage memory. Instead the programmer manages heap memory manually. All this makes C fast but fragile. Perl and Java are more "portable" than C (you can run them on different computers without a recompile). Java and C++ are more structured than C. Structure is useful for large projects. C works best for small projects where performance is important and the programmers have the time and skill to make it work in C. In any case, C is a very popular and influential language. This is mainly because of C's clean (if minimal) style, it's lack of annoying or regrettable constructs, and the relative ease of writing a C compiler.
27 Day 1 2. Data type, operator and expression Data types and sizes - Integer - Floating point type - Pointer - Array - Enum Constant Variable Declaration and Definition Operator - Assignment operator and expression - Arithmetic operator - Relational operator - Conditional operator Bit wise operator Type conversion Conditional expression C provides a standard, minimal set of basic data types. Sometimes these are called "primitive" types. More complex data structures can be built up from these basic types. Integer Types The "integral" types in C form a family of integer types. - char ASCII character -- at least 8 bits. 8 bits provides a signed range of or an unsigned range is char is also required to be the "smallest addressable unit" - short Small integer -- at least 16 bits which provides a signed range of Typical size is 16 bits. - int Default integer -- at least 16 bits, with 32 bits being typical. Defined to be the "most comfortable" size for the computer. - long Large integer -- at least 32 bits. Typical size is 32 bits which gives a signed range of about -2 billion..+2 billion. Some compilers support "long long" for 64 bit ints. The integer types can be preceded by the qualifier unsigned which disallows representing negative numbers, but doubles the largest positive number representable. Extra: Portability Problems It is a good idea to use typedefs to set up types like Int32 for 32 bit int and Int16 for 16 bit int. It makes it processor architecture independent. Various typedef are available in stdint.h
28 <<stdint.h> #ifndef int8_t_defined # define int8_t_defined typedef signed char typedef short int typedef int # if WORDSIZE == 64 typedef long int # else extension typedef long long int # endif #endif int8_t; int16_t; int32_t; int64_t; int64_t; /* Unsigned. */ typedef unsigned char uint8_t; typedef unsigned short int uint16_t; #ifndef uint32_t_defined typedef unsigned int uint32_t; # define uint32_t_defined #endif #if WORDSIZE == 64 typedef unsigned long int uint64_t; #else extension typedef unsigned long long int uint64_t; #endif... char Constants 'A' uppercase 'A' character '\n' newline character '\t' tab character '\0' the "null" character -- integer value 0 (different from the char digit '0') '\012' the character with value 12 in octal, which is decimal 10 Integer constants Numbers in the source code such as 234 default to type int. They may be followed by an 'L' (upper or lower case) to designate that the constant should be a long such as 42L. An integer constant can be written with a leading 0x to indicate that it is expressed in hexadecimal -- 0x10 is way of expressing the number 16. Similarly, a constant may be written in octal by preceding it with "0" 012 is a way of expressing the number 10.
29 Type Combination and Promotion The integral types may be mixed together in arithmetic expressions since they are all basically just integers with variation in their width. For example, char and int can be combined in arithmetic expressions such as ('b' + 5), int and long like (5+10L). Pitfall -- int Overflow (k*1024) may not work when k is int in low address bit memory. Way to fix the code is to rewrite it as (k * 1024L) -- the long constant forced the promotion of the int. Floating point Types float Single precision floating point number typical size: 32 bits double precision floating point number typical size: 64 bits long double possibly even bigger floating point number (somewhat obscure) Constants in the source code such as 3.14 default to type double unless the are suffixed with an 'f' (float) or 'l' (long double). Single precision equates to about 6 digits of precision and double is about 15 digits of precision. floating point numbers is that they are inexact (1.0/ / /3.0) // is this equal to 1.0 exactly? - Do not Use equality (==) -- use inequality (<) comparisons instead. Array An array is a data structure which can store a fixed-size sequential collection of elements of the same type. score v x <-do not use int score[100];
30 Array declaration - type arrayname[arraysize] float a[5]; int x,y,b[5]; Array Initialization int a[5]=(1,3,5,;//rest initialized with 0 int a[]={1,3,5,7,9; int age[2][3]={{4,8,12,{19,6,-1 0th col 1st col 2nd col th row st row th row 1st row 0th col 1st col 2nd col 0th col 1st col 2nd col Passing array argument int func(int score[2][3]) int func(int score[][3]){ int func(int (*score)[3]){ func(a);//pass by address, value changed in func Pointer A pointer is a value which represents a reference to another value sometimes known as the pointer's "pointee". Pointer operators * (Deference operator) - means "the value of" & (address-of operator) - means "address of" int a=5; 5000 a-> <----+ int *pa=&a; 6000 pa-> <----+
31 struct fraction { int numerator; int denominator; ; struct fraction *f1, *f2; denominator f numerator ^ > / struct fraction* struct fraction (the whole block of memory) expression Type f1 struct fraction* *f1 struct fraction (*f1).numerator int complex declarations struct fraction** fp; a pointer to a pointer to a struct fraction struct fraction fract_array[20]; array of 20 struct fraction struct fraction *fract_ptr_array[20]; an array of 20 pointers to struct fraction struct fraction (*pfa)[100]; struct fraction (*(*pf)())(); f(int daytab[2][13]) {... It could also be f(int daytab[][13]) {... Since the number of rows is irrelevant, or it could be f(int (*daytab)[13]) {... Which says that the parameter is a pointer to an array of 13 integers. The parentheses are necessary since brackets [] have higher precedence than *. Without parentheses, the declaration would be int *daytab[13] // array of pointer to ints There is an important difference between these definitions: char amessage[] = "now is the time"; /* an array */ char *pmessage = "now is the time"; /* a pointer */ char (*(*x())[])() x: function returning pointer to array[] of pointer to function returning char char (*(*x[3])())[5] x: array[3] of pointer to function returning pointer to array[5] of char
32 Dynamic allocation malloc : memory allocation free : memory deallocation int *intptr; char *charpt; intptr=(int*)malloc(sizeof(int)); charptr=(char*)malloc(sizeof(char)*6); free(intptr); free(charptr); Memory leak - Memory allocated is not de-allocated. Dangling pointer - A pointer that points to a variable that has been de-allocated. Pointer arithmetic int *pi; char *pc; ++pi;//jumps 4 bytes in 32 bit processor ++pc;//jumps 1 byte Array & Pointers int a[10]; int *b=&a[0]; const char *pc="string"; char ac[]="string"; pc > Pointer to a block of memeory ac Array of memory fragments. No address Enum An enumeration is a list of constant integer values. enum boolean { NO, YES ; enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC ; /* FEB = 2, MAR = 3, etc. */ eum {No,YES; // global boolean value=no;
33 $cat main.c #include <stdio.h> struct SomeItem{ enum {MOVIE,MUSIC itemtype; union{ int movieid; char moviename[255]; ; ; int main(int argc, char *argv[]){ struct SomeItem someitem; someitem.itemtype=music; someitem.movieid=10; return 0; Day 1 2. Data type, operator and expression Data types and sizes - Integer - Floating point type - Pointer - Array - Enum Constant Variable Declaration and Definition Operator - Assignment operator and expression - Arithmetic operator - Relational operator - Conditional operator Bit wise operator Type conversion Conditional expression Const The qualifier const can be added to the left of a variable or parameter type to declare that the code using the variable will not change the variable. void foo(const struct fraction* fract); int i, *pi, *const cpi = &i; const int j=func(); char amessage[] = "now is the time"; /* an array */ char *pmessage = "now is the time"; /* a pointer */ const int *p; // pointer to constant int * const p;//const pointer to integer const int * const p;//const pointer to integer const Const must be defined or initialized at the time of declaration. Const has internal linkage similar to static.
34 Day 1 2. Data type, operator and expression Data types and sizes - Integer - Floating point type - Pointer - Array - Enum Constant Variable Declaration and Definition Operator - Assignment operator and expression - Arithmetic operator - Relational operator - Conditional operator Bit wise operator Type conversion Conditional expression Declaration - Asserts the existence of a variable, function or type defined elsewhere in the program. A variable may be declared by preceding its type with the keyword extern. const declaration are file scope and must be initialized or defined at the time of declaration. static variable and functions are file scoped and they can not be defined in other files like extern. $ cat a.c extern int a; extern const int b=10; $ cat b.c #include <stdio.h> int a=10;//defined here const int b=20; // error while linking int main(){ return 0; $ gcc -c a.c -o a.o a.c:2: warning: b initialized and declared extern $ gcc -c b.c -o b.o $ gcc -o aa a.o b.o b.o:(.rodata+0x0): multiple definition of `b' a.o:(.rodata+0x0): first defined here collect2: ld returned 1 exit status int a; // just declaration void func();//just declaration c++ int a // declaration and definition extern a // declaration
35 Declaration can be made multiple times. Definition - Allocates storage for a variable of a specified type and optionally initializes the variable int a=10; //declaration and definition void func(){// declaration and definition - Definition must be only once. Day 1 2. Data type, operator and expression Data types and sizes - Integer - Floating point type - Pointer - Array - Enum Constant Variable Declaration and Definition Operator - Assignment operator and expression - Arithmetic operator - Relational operator - Conditional operator Bit wise operator Type conversion Conditional expression An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. - Assignment operator and expression Here's the list of assignment shorthand operators... +=, -= Increment or decrement by RHS *=, /= Multiply or divide by RHS %= Mod by RHS >>= Bitwise right shift by RHS (divide by power of 2) <<= Bitwise left shift RHS (multiply by power of 2) &=, =, ^= Bitwise and, or, xor by RHS - Arithmetic Operators + Addition - Subtraction / Division * Multiplication % Remainder (mod)
36 - Unary Increment Operators: The unary ++ and -- operators increment or decrement the value in a variable. var++ //post variant ++var //pre variant - Relational Operators These operate on integer or floating point values and return a 0 or 1 boolean value. == Equal!= Not Equal > Greater Than < Less Than >= Greater or Equal <= Less or Equal Problem. while(x=3);//legal while(x==3);//legal - Logical Operators The value 0 is false, anything else is true.! Boolean not (unary) && Boolean and Boolean or - Conditional Operators?: Exp1? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. - Misc Operators sizeof() Returns the size of an variable & Returns the address of an variable * Pointer to a variable
37 Day 1 2. Data type, operator and expression Data types and sizes - Integer - Floating point type - Pointer - Array - Enum Constant Variable Declaration and Definition Operator - Assignment operator and expression - Arithmetic operator - Relational operator - Conditional operator Bit wise operator Type conversion Conditional expression Bitwise Operators C includes operators to manipulate memory at the bit level. ~ Bitwise Negation (unary) flip 0 to 1 and 1 to 0 throughout & Bitwise And Bitwise Or ^ Bitwise Exclusive Or >> Right Shift by right hand side (RHS) (divide by power of 2) << Left Shift by RHS (multiply by power of 2) - Note & and && are different unsigned int a = 60; /* 60 = */ unsigned int b = 13; /* 13 = */ int c = 0; c = a & b; /* 12 = */ printf("line 1 - Value of c is %d\n", c ); c = a b; /* 61 = */ printf("line 2 - Value of c is %d\n", c ); c = a ^ b; /* 49 = */ printf("line 3 - Value of c is %d\n", c ); c = ~a; /*-61 = */ printf("line 4 - Value of c is %d\n", c ); c = a << 2; /* 240 = */ printf("line 5 - Value of c is %d\n", c ); c = a >> 2; /* 15 = */
38 Day 1 - Morning 2. Data type, operator and expression Data types and sizes - Integer - Floating point type - Pointer - Array - Enum Constant Variable Declaration and Definition Operator - Assignment operator and expression - Arithmetic operator - Relational operator - Conditional operator Bit wise operator Type conversion Conditional expression When an operator has operands of different types, they are converted to a common type according to a small number of rules. In general, the only automatic conversions are those that convert a promotion "narrower" operand into "wider" one without losing information, such as converting an integer into floating point in an expression like f + i. Truncation Expressions that might lose information, like assigning a longer integer type to a shorter, or a floating-point type to an integer, may draw a warning, but they are not illegal.
39 2. Data type, operator and expression Data types and sizes - Integer - Floating point type - Pointer - Array - Enum Constant Variable Declaration and Definition Operator - Assignment operator and expression - Arithmetic operator - Relational operator - Conditional operator Bit wise operator Type conversion Conditional expression Conditional Expression?: Exp1? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions.
40 Day 1 Afternoon 3. Array Pointers References Defining and initializing Array. Defining and initializing Pointers. Using pointers to access array elements. Pointers and const qualifiers. Dynamically allocated arrays. Multidimensional array argument to function - Define and initialize static array - Array has to be initialized with constant variable that is qualified at compile time int ia[get_size()] // get_size() is function and resolved at run time const int size=get_size(); // size resolved at run time int ia[size]; // error int ia[10*2-10]; // resolved at compile time - Local copy are uninitialized where as global copy is initialized to 0. - Uninitialized stati c or global array goes to.bss section in the binary. - Array is initialized in { block int arr[]={1,2,3 // array size 3 or Int arr[3]={1,2,3 Int arr[5]={1,2,3 // rest initialized with 0 Uninitialized const array takes garbage value const int arr[3];// garbage value C++ const uninitialized array is an error const int arr[3]={1; // rest initialized with 0 const int *arr=new arr[3]() // c++ value initialized Breaking array boundary is not an exception and it memory over writing int ary[1]; ary[2]=0; Function array arguments are actually pointer to array. void func(int ap[4]); Void func(int ap[]); void func(int *ap); //all are same func (arr);
41 -Pointer to array and multidimensional array void func(int (*arr)[10]); void func(int arr[][10]); void func(int arr[4][10]);// all same - Array can not be copied or assigned int ia2[](ia); // error ia2 = ia1; //error - Array size can not be known. sizeof(arr)/sizeof(&arr[0]) - Array memory management is in users hand. Chance of memory overwriting. void func(int pa[6]){ pa[6]=8; int pa[4]; func(pa); - Character array can be initialized with string null terminated. char ca[] = "C++"; - Character array can be initialized character wise, many not be null terminated char cal[] = {'C', '+', '+', '\0' ; - In case of character strings use strn string function for manipulation, si.e strncpy, strncat. 3. Array Pointers References Defining and initializing Array. Defining and initializing Pointers. Using pointers to access array elements. Pointers and const qualifiers. Dynamically allocated arrays. Multidimensional array argument to function type * pointer_name[,*pointer,name2,..]; char * terry = "hello"; //character string const char *terry;//pointer to constant char char *const terry;//const pointer to char const char *const terry;//const pointer to char const
42 Various library function involving char pointer manipulation str[n]cpy,str[n]cat,str[n]cmp,strdup,bcopy,memccopy, memcpy,memmove,string,wcscpy,wcsncpy,index, rindex, strcasecmp,strchr,strcmp, strcoll, strcspn, strfry, strlen,strncasecmp, strpbrk, strrchr,strsep, strspn, strstr, strtok, strxfrm - Dynamically allocating array, allocating on heap - void *realloc(void *ptr, size_t size);// buffer remain uninitialized int pia = malloc(sizeof(int)*10); // uninitialized - void *realloc(void *ptr, size_t size);// initialized buffer with char 0; int pia=calloc(sizeof(int)*10); - void *realloc(void *ptr, size_t size);// re-allocate uninitialized buffer of new size if continuous memory is available for new size. int pia=malloc(sizeof(int)*10); pia=realloc(sizeof(int)*20); If run on empty buffer malloc is called. 0 size free the memory - void *realloc(void *ptr, size_t size);, frees the allocated memory free(pia); - Its legal to dynamically allocate empty array unless dereferenced char arr[0]; // error char arr = new char[0];// ok char arr = new char[get_size()];//get_size() can return 0; Day 1 Afternoon 3. Array Pointers References Defining and initializing Array. Defining and initializing Pointers. Using pointers to access array elements. Pointers and const qualifiers. Dynamically allocated arrays. Multidimensional array argument to function - Pointer works in dynamic allocation - Array of pointers classa *arrp=new classa[10];
CSE 333 Lecture 2 Memory
CSE 333 Lecture 2 Memory John Zahorjan Department of Computer Science & Engineering University of Washington Today s goals - some terminology - review of memory resources - reserving memory - type checking
More informationC Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:
C Programming Code: MBD101 Duration: 10 Hours Prerequisites: You are a computer science Professional/ graduate student You can execute Linux/UNIX commands You know how to use a text-editing tool You should
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationA Fast Review of C Essentials Part I
A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types
More informationStudy and Analysis of ELF Vulnerabilities in Linux
Study and Analysis of ELF Vulnerabilities in Linux Biswajit Sarma Assistant professor, Department of Computer Science and Engineering, Jorhat Engineering College, Srishti Dasgupta Final year student, Department
More informationFrom Website:
From Website: http://resources.infosecinstitute.com/hello-world-c-assembly-object-file-and-executable/ Hello World: C, Assembly, Object File and Executable By Dejan Lukan January 7th, 2013 Introduction
More informationDraft. 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
Chapter 1 Program Structure In the beginning there were 0s and 1s. GRR 1.1 Introduction In this chapter we will talk about memory: bits, bytes and how data is represented in the computer. We will also
More informationUNIT- 3 Introduction to C++
UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage
More informationCS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation
CS113: Lecture 3 Topics: Variables Data types Arithmetic and Bitwise Operators Order of Evaluation 1 Variables Names of variables: Composed of letters, digits, and the underscore ( ) character. (NO spaces;
More informationIMPORTANT QUESTIONS IN C FOR THE INTERVIEW
IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.
More informationLink 3. Symbols. Young W. Lim Mon. Young W. Lim Link 3. Symbols Mon 1 / 42
Link 3. Symbols Young W. Lim 2017-09-11 Mon Young W. Lim Link 3. Symbols 2017-09-11 Mon 1 / 42 Outline 1 Linking - 3. Symbols Based on Symbols Symbol Tables Symbol Table Examples main.o s symbol table
More informationCS Programming In C
CS 24000 - Programming In C Week Two: Basic C Program Organization and Data Types Zhiyuan Li Department of Computer Science Purdue University, USA 2 int main() { } return 0; The Simplest C Program C programs
More informationCOMP322 - Introduction to C++ Lecture 02 - Basics of C++
COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.
More informationTypes, Operators and Expressions
Types, Operators and Expressions EECS 2031 18 September 2017 1 Variable Names (2.1) l Combinations of letters, numbers, and underscore character ( _ ) that do not start with a number; are not a keyword.
More informationTopic 6: A Quick Intro To C
Topic 6: A Quick Intro To C Assumption: All of you know Java. Much of C syntax is the same. Also: Many of you have used C or C++. Goal for this topic: you can write & run a simple C program basic functions
More informationTypes, Operators and Expressions
Types, Operators and Expressions CSE 2031 Fall 2011 9/11/2011 5:24 PM 1 Variable Names (2.1) Combinations of letters, numbers, and underscore character ( _ ) that do not start with a number; are not a
More informationP.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above
P.G.TRB - COMPUTER SCIENCE Total Marks : 50 Time : 30 Minutes 1. C was primarily developed as a a)systems programming language b) general purpose language c) data processing language d) none of the above
More informationWork relative to other classes
Work relative to other classes 1 Hours/week on projects 2 C BOOTCAMP DAY 1 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Overview C: A language
More informationBasic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island
Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Data Types Basic Types Enumerated types The type void Derived types
More informationLectures 5-6: Introduction to C
Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most
More informationContents. Preface. Introduction. Introduction to C Programming
c11fptoc.fm Page vii Saturday, March 23, 2013 4:15 PM Preface xv 1 Introduction 1 1.1 1.2 1.3 1.4 1.5 Introduction The C Programming Language C Standard Library C++ and Other C-Based Languages Typical
More informationBasic Types, Variables, Literals, Constants
Basic Types, Variables, Literals, Constants What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet) But some machines had 7, or 9, or... A word is the basic
More informationLink 8. Dynamic Linking
Link 8. Dynamic Linking Young W. Lim 2018-12-27 Thr Young W. Lim Link 8. Dynamic Linking 2018-12-27 Thr 1 / 66 Outline 1 Linking - 8. Dynamic Linking Based on Dynamic linking with a shared library example
More informationFile Handling in C. EECS 2031 Fall October 27, 2014
File Handling in C EECS 2031 Fall 2014 October 27, 2014 1 Reading from and writing to files in C l stdio.h contains several functions that allow us to read from and write to files l Their names typically
More informationCSE2421 Systems1 Introduction to Low-Level Programming and Computer Organization
Spring 2013 CSE2421 Systems1 Introduction to Low-Level Programming and Computer Organization Kitty Reeves TWRF 8:00-8:55am 1 Compiler Drivers = GCC When you invoke GCC, it normally does preprocessing,
More informationAppendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.
A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators
More information6.096 Introduction to C++ January (IAP) 2009
MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture
More informationMemory and C/C++ modules
Memory and C/C++ modules From Reading #5 and mostly #6 More OOP topics (templates; libraries) as time permits later Program building l Have: source code human readable instructions l Need: machine language
More informationTopic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History
Topic 6: A Quick Intro To C Reading Assumption: All of you know basic Java. Much of C syntax is the same. Also: Some of you have used C or C++. Goal for this topic: you can write & run a simple C program
More informationCharacter Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits
More informationINTRODUCTION 1 AND REVIEW
INTRODUTION 1 AND REVIEW hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Programming: Advanced Objectives You will learn: Program structure. Program statements. Datatypes. Pointers. Arrays. Structures.
More informationCS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco
CS 326 Operating Systems C Programming Greg Benson Department of Computer Science University of San Francisco Why C? Fast (good optimizing compilers) Not too high-level (Java, Python, Lisp) Not too low-level
More informationCS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor
CS 261 Fall 2017 Mike Lam, Professor C Introduction Variables, Memory Model, Pointers, and Debugging The C Language Systems language originally developed for Unix Imperative, compiled language with static
More informationBinghamton University. CS-220 Spring Loading Code. Computer Systems Chapter 7.5, 7.8, 7.9
Loading Code Computer Systems Chapter 7.5, 7.8, 7.9 gcc g o ttt ttt.c ttt.c ttt gcc gcc g o ttt ttt.c ttt.c gcc ttt Pre-Processor Linker Compiler Assembler ttt.s ttt.o What is in a binary executable file?
More informationBLM2031 Structured Programming. Zeyneb KURT
BLM2031 Structured Programming Zeyneb KURT 1 Contact Contact info office : D-219 e-mail zeynebkurt@gmail.com, zeyneb@ce.yildiz.edu.tr When to contact e-mail first, take an appointment What to expect help
More informationReview of the C Programming Language for Principles of Operating Systems
Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights
More informationMotor Industry Software Reliability Association (MISRA) C:2012 Standard Mapping of MISRA C:2012 items to Goanna checks
Goanna 3.3.2 Standards Data Sheet for MISRA C:2012 misrac2012-datasheet.pdf Motor Industry Software Reliability Association (MISRA) C:2012 Standard Mapping of MISRA C:2012 items to Goanna checks The following
More informationReminder: compiling & linking
Reminder: compiling & linking source file 1 object file 1 source file 2 compilation object file 2 library object file 1 linking (relocation + linking) load file source file N object file N library object
More informationReview of the C Programming Language
Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the
More informationDesign and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso
Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso Why C? Test on 21 Android Devices with 32-bits and 64-bits processors and different versions
More informationIntroduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers
Introduction to C Geared toward programmers Robert Escriva Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Cornell CS 4411, August 30, 2010 1 Why C? 2 A Quick Example 3 Programmer s Responsibilities
More informationDynamic libraries explained
Dynamic libraries explained as seen by a low-level programmer I.Zhirkov 2017 1 Exemplary environment Intel 64 aka AMD64 aka x86_64. GNU/Linux Object file format: ELF files. Languages: C, Assembly (NASM)
More informationExecutables and Linking. CS449 Spring 2016
Executables and Linking CS449 Spring 2016 Remember External Linkage Scope? #include int global = 0; void foo(); int main() { foo(); printf( global=%d\n, global); return 0; } extern int
More informationSyntax and Variables
Syntax and Variables What the Compiler needs to understand your program, and managing data 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line
More informationPractical Malware Analysis
Practical Malware Analysis Ch 4: A Crash Course in x86 Disassembly Revised 1-16-7 Basic Techniques Basic static analysis Looks at malware from the outside Basic dynamic analysis Only shows you how the
More information238P: Operating Systems. Lecture 7: Basic Architecture of a Program. Anton Burtsev January, 2018
238P: Operating Systems Lecture 7: Basic Architecture of a Program Anton Burtsev January, 2018 What is a program? What parts do we need to run code? Parts needed to run a program Code itself By convention
More informationC++ Programming Basics
C++ Programming Basics Chapter 2 and pp. 634-640 Copyright 1998-2011 Delroy A. Brinkerhoff. All Rights Reserved. CS 1410 Chapter 2 Slide 1 of 25 Program Components Function main P Every C/C++ program has
More informationEL6483: Brief Overview of C Programming Language
EL6483: Brief Overview of C Programming Language EL6483 Spring 2016 EL6483 EL6483: Brief Overview of C Programming Language Spring 2016 1 / 30 Preprocessor macros, Syntax for comments Macro definitions
More informationC OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure
C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces
More informationC OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed
C Overview C OVERVIEW Goals speed portability allow access to features of the architecture speed C fast executables allows high-level structure without losing access to machine features many popular languages
More informationPRINCIPLES OF OPERATING SYSTEMS
PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)
More informationFundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University
Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler
More informationC++ Programming: From Problem Analysis to Program Design, Third Edition
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine
More informationPreview from Notesale.co.uk Page 6 of 52
Binary System: The information, which it is stored or manipulated by the computer memory it will be done in binary mode. RAM: This is also called as real memory, physical memory or simply memory. In order
More informationCS240: Programming in C
CS240: Programming in C Lecture 2: Hello World! Cristina Nita-Rotaru Lecture 2/ Fall 2013 1 Introducing C High-level programming language Developed between 1969 and 1973 by Dennis Ritchie at the Bell Labs
More informationELF (1A) Young Won Lim 3/24/16
ELF (1A) Copyright (c) 21-216 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version
More informationBasic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island
Basic C Programming Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Announcements Exam 1 (20%): Feb. 27 (Tuesday) Tentative Proposal Deadline:
More informationComputer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary
GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis
More informationCSci 4061 Introduction to Operating Systems. Programs in C/Unix
CSci 4061 Introduction to Operating Systems Programs in C/Unix Today Basic C programming Follow on to recitation Structure of a C program A C program consists of a collection of C functions, structs, arrays,
More information>B<82. 2Soft ware. C Language manual. Copyright COSMIC Software 1999, 2001 All rights reserved.
>B
More informationTeensy Tiny ELF Programs
Teensy Tiny ELF Programs inspired by Brian Raiter Roland Hieber Stratum 0 e. V. March 15, 2013 1 / 14 Hello World # include int main ( int argc, char ** argv ) { printf (" Hello World!\n"); return
More informationLinux on zseries ABI and Linkage Format SHARE 102 Session 9236
Linux on zseries ABI and Linkage Format SHARE 102 Session 9236 Dr. Ulrich Weigand Linux on zseries Development, IBM Lab Böblingen Ulrich.Weigand@de.ibm.com Agenda Compiling, linking, and loading Function
More informationFundamental of C programming. - Ompal Singh
Fundamental of C programming - Ompal Singh HISTORY OF C LANGUAGE IN 1960 ALGOL BY INTERNATIONAL COMMITTEE. IT WAS TOO GENERAL AND ABSTRUCT. IN 1963 CPL(COMBINED PROGRAMMING LANGUAGE) WAS DEVELOPED AT CAMBRIDGE
More informationLecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?
Lecture 14 No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions? Friday, February 11 CS 215 Fundamentals of Programming II - Lecture 14 1 Outline Static
More informationOperating Systems CMPSC 473. Process Management January 29, Lecture 4 Instructor: Trent Jaeger
Operating Systems CMPSC 473 Process Management January 29, 2008 - Lecture 4 Instructor: Trent Jaeger Last class: Operating system structure and basics Today: Process Management Why Processes? We have programs,
More informationCODE TIME TECHNOLOGIES. Abassi RTOS MISRA-C:2004. Compliance Report
CODE TIME TECHNOLOGIES Abassi RTOS MISRA-C:2004 Compliance Report Copyright Information This document is copyright Code Time Technologies Inc. 2012. All rights reserved. No part of this document may be
More informationArrays and Pointers. CSE 2031 Fall November 11, 2013
Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example
More informationFeatures of C. Portable Procedural / Modular Structured Language Statically typed Middle level language
1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC
More informationVariables Data types Variable I/O. C introduction. Variables. Variables 1 / 14
C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition
More informationCSCI 171 Chapter Outlines
Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures
More information9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C
Overview The C Programming Language (with material from Dr. Bin Ren, William & Mary Computer Science) Motivation Hello, world! Basic Data Types Variables Arithmetic Operators Relational Operators Assignments
More informationC Introduction. Comparison w/ Java, Memory Model, and Pointers
CS 261 Fall 2018 Mike Lam, Professor C Introduction Comparison w/ Java, Memory Model, and Pointers Please go to socrative.com on your phone or laptop, choose student login and join room LAMJMU The C Language
More informationUnder the Hood: Data Representations, Memory and Bit Operations. Computer Science 104 Lecture 3
Under the Hood: Data Representations, Memory and Bit Operations Computer Science 104 Lecture 3 Homework #1 Due Feb 6 Reading TAs Finish Chapter 1 Start Chapter 2 Admin +1 UTA: Michael Zhou Lindsay is Head
More informationBITG 1233: Introduction to C++
BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token
More informationcs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).
cs3157: another C lecture (mon-21-feb-2005) C pre-processor (1). today: C pre-processor command-line arguments more on data types and operators: booleans in C logical and bitwise operators type conversion
More informationCS 376b Computer Vision
CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves
More informationObjectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program
Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationProgramming in C - Part 2
Programming in C - Part 2 CPSC 457 Mohammad Reza Zakerinasab May 11, 2016 These slides are forked from slides created by Mike Clark Where to find these slides and related source code? http://goo.gl/k1qixb
More informationChapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationThe C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)
The C Programming Language (with material from Dr. Bin Ren, William & Mary Computer Science) 1 Overview Motivation Hello, world! Basic Data Types Variables Arithmetic Operators Relational Operators Assignments
More informationCS201 Latest Solved MCQs
Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability
More informationUNIT - I. Introduction to C Programming. BY A. Vijay Bharath
UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been
More informationChapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction
Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers
More informationCS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010
CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please
More informationSISTEMI EMBEDDED. The C Pre-processor Fixed-size integer types Bit Manipulation. Federico Baronti Last version:
SISTEMI EMBEDDED The C Pre-processor Fixed-size integer types Bit Manipulation Federico Baronti Last version: 20180312 The C PreProcessor CPP (1) CPP is a program called by the compiler that processes
More informationCS201 Some Important Definitions
CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data
More informationC Review. MaxMSP Developers Workshop Summer 2009 CNMAT
C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***
More informationget.c get.o extern int a[]; int get_a(int i) { return a[i]; }
get.c get.o extern int a[]; int get_a(int i) { return a[i]; } get.o get get.o get.so ELF ELF segments sections https://en.wikipedia.org/wiki/executable_and_linkable_format ELF https://en.wikipedia.org/wiki/executable_and_linkable_format
More informationCMPE-013/L. Introduction to C Programming
CMPE-013/L Introduction to C Programming Bryant Wenborg Mairs Spring 2014 What we will cover in 13/L Embedded C on a microcontroller Specific issues with microcontrollers Peripheral usage Reading documentation
More informationComputers Programming Course 5. Iulian Năstac
Computers Programming Course 5 Iulian Năstac Recap from previous course Classification of the programming languages High level (Ada, Pascal, Fortran, etc.) programming languages with strong abstraction
More informationArrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.
Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example
More informationSISTEMI EMBEDDED. The C Pre-processor Fixed-size integer types Bit Manipulation. Federico Baronti Last version:
SISTEMI EMBEDDED The C Pre-processor Fixed-size integer types Bit Manipulation Federico Baronti Last version: 20170307 The C PreProcessor CPP (1) CPP is a program called by the compiler that processes
More informationC Programming SYLLABUS COVERAGE SYLLABUS IN DETAILS
C Programming C SYLLABUS COVERAGE Introduction to Programming Fundamentals in C Operators and Expressions Data types Input-Output Library Functions Control statements Function Storage class Pointer Pointer
More informationRule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.
Chapter 9: Rules Chapter 1:Style and Program Organization Rule 1-1: Organize programs for readability, just as you would expect an author to organize a book. Rule 1-2: Divide each module up into a public
More informationQuiz Start Time: 09:34 PM Time Left 82 sec(s)
Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability
More informationReview: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements
Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering
More informationDEPARTMENT OF MATHS, MJ COLLEGE
T. Y. B.Sc. Mathematics MTH- 356 (A) : Programming in C Unit 1 : Basic Concepts Syllabus : Introduction, Character set, C token, Keywords, Constants, Variables, Data types, Symbolic constants, Over flow,
More informationTokens, Expressions and Control Structures
3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type
More information