Learn C Programming Under Linux: Basics and Examples

c programming under linux n.w
1 / 31
Embed
Share

"Discover the fundamentals of C programming under Linux with practical examples. Explore topics like input/output, command line arguments, and pointers to enhance your skills in C programming. Get started today!"

  • Linux
  • C Programming
  • Examples
  • Basics
  • Pointers

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. C Programming under Linux 1

  2. My first C program! #include <stdio.h> //hello world program int main() { printf ("Hello world!\n"); return 0; } #include <stdio.h> int main() { int number; scanf( %d , &number); printf( %d\n , number); return 0; } & in scanf(). It is used to access the address of the variable used. scanf( %d ,&a); we are reading into the address of a. Create example file: try.c Compile using gcc: $ gcc o try try.c The standard C library libc is included automatically Execute program using : $./try 2

  3. Example 2 #include <stdio.h> // program reads int and prints it back int main() { int number ; printf ( Enter a Number: ); scanf ( %d , &number); printf ( Number is %d\n , number); return 0; } Output : Enter a number: 4 Number is 4 3

  4. Another Example C Program #include directs the preprocessor to include the contents of the file at this point in the source file. #define directs preprocessor to define macros. /usr/include/stdio.h /* comments */ #ifndef _STDIO_H #define _STDIO_H example.c /* this is a C-style comment * You generally want to palce * all file includes at start of file * */ #include <stdio.h> #include <stdlib.h> ... definitions and protoypes #endif /usr/include/stdlib.h /* prevents including file * contents multiple * times */ #ifndef _STDLIB_H #define _STDLIB_H int main (int argc, char **argv) { // this is a C++-style comment // printf prototype in stdio.h printf( Prog name = %s\n , argv[0]); exit(0); } ... definitions and protoypes #endif

  5. Passing Command Line Arguments When you execute a program you can include arguments on the command line. ./try g 2 fred The run time environment will create an argument vector. argc = 4, argv = <address0> argv is the argument vector argc is the number of arguments Argument vector is an array of pointers to strings. t r y \0 argv: a string is an array of characters terminated by a binary 0 (NULL or \0 ). [0] <addres1> [1] <addres2> [2] <addres3> [3] <addres4> [4] NULL - g \0 argv[0] is always the program name, so argc is at least 1. 2 \0 f r e d \0

  6. Another Simple C Program int main (int argc, char **argv) { int i; printf( There are %d arguments\n , argc); for (i = 0; i < argc; i++) printf( Arg %d = %s\n , i, argv[i]); return 0; } Notice that the syntax is similar to Java What s new in the above simple program? of course you will have to learn the new interfaces and utility functions defined by the C standard and UNIX Pointers will give you the most trouble

  7. Input / Output printf(); //used to print to console(screen) scanf(); //used to take an input from console(user). E.g.: printf( %c , a ); scanf( %d , &a); More format specifiers %c The character format specifier. %d The integer format specifier. %i The integer format specifier (same as %d). %f The floating-point format specifier. %o The unsignedoctal format specifier. %s The string format specifier. %u The unsignedinteger format specifier. %x The unsignedhexadecimal format specifier. %% Outputs a percentsign. 7

  8. How to Write and Run a C Program in Linux Step 1: Install the build-essential packages $ sudo apt-get install build-essential Step 2: Write a simple C program $ pico sample.c Step 3: Compile the C program with gcc Compiler $ gcc [programName].c -o programName $ gcc sample.c -o sample $ gcc sample.c Step 4: Run the program $ ./programName $ ./sample $ ./a.out 8

  9. Programming on Linux contd Writing programs Use any editor (graphical, console) Save file as <filename>.c Compiling programs gcc <filename>.c gcc sample.c o sample Running programs ./a.out executable files need to have executable permissions. $chmod +x <executable> ./sample 9

  10. Compilation is not a single stage Pre process : cpp (C Preprocessor) gcc E Removes comments, includes #include files Compile : gcc c (GNU compiler) main step, compilation, change into machine code gcc -g -Wall -c sample.c generates sample.o (an object file). An object file is compiled code with unresolved references. For example, if sample.c uses printf, there will be an unresolved reference to printf in the object file. Link : ld (GNU linker) link executables Note: gcc does all the above steps 10

  11. Linking There is a tool called the linker that puts object files together. This includes resolving references: Linking an object file with an unresolved reference to foo() to an object file with the code for foo() resolves the reference. The linker program is called ld, but you ll almost always just have gcc invoke the linker for you. gcc -g -Wall -c module1.c gcc -g -Wall -c module2.c gcc -g -Wall -c main.c gcc -o program main.o module1.o module2.o gcc implicitly links against the standard C libraries. 11

  12. 2. C on Windows 10 Use a text editor install notepad++ : https://notepad-plus-plus.org/downloads/ Sublime : https://www.sublimetext.com Compiler that generates windows compatible binaries: MinGW : http://www.mingw.org/ Cygwin : https://www.cygwin.com/ 12

  13. Why doesnt my windows binary run on Linux? File format: exe and elf man elf In Linux, program does system calls. Libraries are different 13

  14. Preprocessing We can write methods, declare variable in multiple files. Need to link these. # include<filename>includes the file filename. # define ABC(X) X*X Replaces the occurrences of ABC(z) with z*z. What happens to ABC(z+1)? // try it out What if ABC(X) is already defined? #ifndef - #endif E.g. #ifndef ABC(X) #define ABC(X) X*X #endif

  15. Pre Processor Directives #include #define #if #ifdef #ifndef #else #elif #endif Used for Including Files, Conditional Compilation and Macro Definition

  16. Including Files #include <stdio.h> int main (void){ printf("Hello, world!\n"); return 0; } The #define, #undef, #if, #ifdef, #ifndef, #else, #elif and #endif directives can be used for conditional compilation. #define __WINDOWS__ . . #ifdef __WINDOWS__ #include <windows.h> #else #include <unistd.h> #endif #define __DEBUG__ . . . #ifdef __DEBUG__ printf("trace Msg."); #endif . .

  17. gcc conditional compilation . . #ifdef __WINDOWS__ #include <windows.h> #else #include <unistd.h> #endif . . . #ifdef __DEBUG__ printf("trace Msg."); #endif . . $ gcc myprogram.c -D__DEBUG__ $ gcc myprogram.c -D__WINDOWS__ Or $ gcc myprogram.c -D__WINDOWS__=1

  18. Arrays and Pointers A variable declared as an array represents a contiguous region of memory in which the array elements are stored. int x[5]; // an array of 5 4-byte ints. All arrays begin with an index of 0 little endian byte ordering 0 1 2 3 0 1 2 3 4 memory layout for array x An array identifier is equivalent to a pointer that references the first element of the array int x[5], *ptr; ptr = &x[0] is equivalent to ptr = x; Pointer arithmetic and arrays: int x[5]; x[2] is the same as *(x + 2), the compiler will assume you mean 2 objects beyond element x.

  19. Strings in C No Strings keyword A string is an array of characters. char string[] = hello world ; char *string = hello world ; OR 19

  20. Significance of NULL character \0 char string[] = hello world ; printf( %s , string); Compiler has to know where the string ends \0 denotes the end of string Some more characters (do $man ascii): \n = new line, \t = horizontal tab, \v = vertical tab, \r = carriage return A = 0x41, a = 0x61, \0 = 0x00 20

  21. Pointers and arrays Pointers and arrays are tightly coupled. char a[] = Hello World ; char *p = &a[0]; 21

  22. 2-Dimensional Arrays (Array of arrays) int d[3][2]; Access the point 1, 2 of the array: d[1][2] Initialize (without loops): int d[3][2] = {{1, 2}, {4, 5}, {7, 8}}; 22

  23. More about 2-Dimensional arrays A Multidimensional array is stored in a row major format. A two dimensional case: next memory element to d[0][3] is d[1][0] d[0][0] d[0][1] d[0][2] d[0][3] d[1][0] d[1][1] d[1][2] d[1][3] d[2][0] d[2][1] d[2][2] d[2][3] What about memory addresses sequence of a three dimensional array? next memory element to t[0][0][0] is t[0][0][1] 23

  24. Pointer to Pointer Declaration Place an asterisk P double *P; Address double p is a pointer to a location of type double Place an double asterisks P Address Address double double **P; p is a pointer to a location of type double 24

  25. Pointer to Pointer contd.. #include <stdio.h> int main() { int x, *p, **q; x = 10; p = &x; q = &p; } printf( %d %d %d\n , x, *p, **q); return 0; {program: pointers.c} 25

  26. Dynamic Memory Allocation To allocate memory at run time. malloc(), calloc() both return a void* you ll need to typecast each time. char *p; p = (char *) malloc(1000); /*get 1000 byte space */ int *i; i = (int *) malloc(1000 * sizeof(int)); 26

  27. Dynamic Memory Allocation contd.. To free memory free() free(ptr) frees the space allocated to the pointer ptr int *i; i = (int *)malloc(1000*sizeof(int)); . . . free(i); 27

  28. Pointers to functions A function pointer stores the address of the function. Function pointers allow: call the function using a pointer functions to be passed as arguments to other functions return_type (*function_name)(type arg1, type arg2 ) {program: function_pointer.c} 28

  29. FILE I/O The file pointer FILE *fp; Opening a file FILE *fp = fopen( data.txt , r ); Modes r : read w: write, a: append, r+ : read and create if file does not exist, w+, a+, rb, wb, ab, r+b, r+w, r+a Closing a file fclose(fp); 29

  30. FILE I/O contd fopen() fclose() fputc() fgetc() fputs() fgets() fseek() ftell() fprintf() fscanf() remove() fflush() opens a file closes a file writes a character to a file reads a character from a file writes a string to a file reads a string to a file change file position indicator returns to file position indicator similar to printf(), but to a file instead of console similar to scanf(), but to a file instead of console deletes the file flushes the file pipe Some functions for file I/O 30

  31. Supplement topic I/O from console Reading from console During program execution printf(), scanf(), putc(), getc() Just before execution starts (parameters passed to the program) $ ./a.out 3 aaa bbb cc int main(int argc, char *argv[]) argc: number of arguments (in above case, 5) argv: pointer to array of char pointers 31

More Related Content