Tuesday, July 17, 2012

A simple example of developing C program, patching and applying it to original source file

Purpose : Create a C program, compile it, apply patch to original file
OS Environemnt : Linus
Required Software : gcc
Implementation Steps : 

1. Create a test.c file and put below codes in it :

#include 
#include 

int main()
 {
 printf("\n I'm test\n");
return 0;
}


2. Compile above file and check its output :

$ gcc -o test test.c

$ ./test

I'm test

3. Applying patches or change codes and recompile it : 
Modify test.c and add new lines or codes in it. Lets say new file is test_modifed.c. This file contains following codes :

#include
#include

int main()
 {
 printf("\n I'm kamal \n");
 printf("\nI have added one more line. This comes from modifed code\n" );
return 0;
}


Compile & execute above program now :


$  gcc -o test_modified test_modified.c
$  ./test_modified

 I'm test

I have added one more line. This comes from modifed code


4. Create a patch file : 

Execute following command to create a patch in the same directory.  :

 $ diff -u test.c test_modified.c > test.patch.1

Here test.path.1 will contain following :

$ cat test.patch.1
--- test.c      2012-07-17 07:52:39.000000000 +0530
+++ test_modified.c     2012-07-17 07:54:41.000000000 +0530
@@ -3,5 +3,6 @@
 int main()
  {
  printf("\n I'm kamal \n");
+ printf("\nI have added one more line. This comes from modifed code\n" );
 return 0;
 }


5. Applying above patch to original file :


$ patch -u test.c < test.patch.1
patching file test.c


$ cat test.c
#include
#include
int main()
 {
 printf("\n I'm kamal \n");
 printf("\nI have added one more line. This comes from modifed code\n" );
return 0;
}


6. Reverting back to previous version :

$ patch -R test.c < test.patch.1
patching file test.c


$ cat test.c
#include

#include

int main()
 {
 printf("\n I'm kamal \n");
return 0;
}



7. Dry run : You can do dry-run (test prior to be originally changing codes in test.c)

$ patch -p0 --dry-run test.c < test.patch.1