Thursday, August 15, 2013

Compiling C Program in Linux Part 2

In the second part, we will write and compile the same program using separate headers file and program. This exercise is useful when you are teaming with your colleague or classmate working on a single project. We will also attempt to use makefile for our compilation.

Writing and Compiling C Program using Multiple Programs

We can convert the following program into multiple programs:

#include <stdio.h>
#include <math.h>

double tvm (double rate, int terms, double principal);

int main ( )
{
 double myrate;
 int myterm;
 double myprincipal;
 double myreturn;

 printf ("Please enter the following:\n");
 printf ("Rate of return: ");
 scanf ("%lf", &myrate);
 printf ("\n");

 printf ("Number of terms:(No decimals): ");
 scanf ("%d", &myterm);
 printf ("\n");

 printf ("The principal amount: ");
 scanf ("%lf", &myprincipal);
 printf ("\n");

 myreturn = tvm (myrate, myterm, myprincipal);
 printf ("Your return after %d term is $%.2lf.\n", myterm, myreturn);

 return 0;
}

double tvm (double rate, int terms, double principal)
{
 double dn;
 double pp;
 dn = terms;

 pp = pow (1+rate, dn);
 return principal * pp;
} 


To split this program, we will keep the functions in myfinancial.h and myfinancial1.c. Then we keep the main program in finapp1.c.

The purpose of splitting the program is to allow tvm function to be reuse in another program.

In the file myfinancial.h, we will include all the financial functions that we have created.

#include <math.h>

double tvm (double rate, int terms, double principal);

The file myfinancial1.c will contains the tvm function.

#include "myfinancial.h"

double tvm (double rate, int terms, double principal)
{
 double dn;
 double pp;
 dn = terms;

 pp = pow (1+rate, dn);
 return principal * pp;
} 


To compile the function program
gcc -Wall -c myfinancial1.c -o myfinancial1.o -lm 

This command will just create the object file as myfinancial1.o.

Once the program is compiled, we do not need to compile it again unless there is changes. You can copy the object file myfinancial1.o to your fellow colleague or classmate for testing.

Now, we can write the main application program in finapp1.c as follows:

#include <stdio.h>
#include "myfinancial.h"

int main ( )
{
 double myrate;
 int myterm;
 double myprincipal;
 double myreturn;

 printf ("Please enter the following:\n");
 printf ("Rate of return: ");
 scanf ("%lf", &myrate);
 printf ("\n");

 printf ("Number of terms:(No decimals): ");
 scanf ("%d", &myterm);
 printf ("\n");

 printf ("The principal amount: ");
 scanf ("%lf", &myprincipal);
 printf ("\n");

 myreturn = tvm (myrate, myterm, myprincipal);
 printf ("Your return after %d term is $%.2lf.\n", myterm, myreturn);

 return 0;
}

To compile finapp1.c:
gcc -Wall finapp1.c myfinancial1.o -lm -o finapp1 


With the object file available, we can create another program finapp2.c using the same tvm function:

#include <stdio.h>
#include "myfinancial.h"

int main ()
{
 double rate = 0.025;
 int term = 10;
 double principal = 1000;
 double result = 0;

 result = tvm (rate, term, principal);

 printf ("The return of $1000 investment with a rate of 2.5 percent in 10 years will give you $%.2lf.\n", result);
 return 0;
}

To compile finapp2.c:
gcc -Wall finapp2.c myfinancial1.o -lm -o finapp2 


Group Programming
In a large programming project involving a team, you need to design the basic structure of the programs. Then you decide on all the necessary functions required in the program. You can also group all the functions into several modules. Each programmer will be responsible for each modules. Each modules contains a header file and a program file. It is important that the header file is completed during the design phase. Using the above method, you can compile the program when all functions and modules are completed.


Compiling C Program using Makefile

Using the example in the previous section, instead of compiling line by line, we can create a make file that will follow certain compiling instructions.

The format for the make file is:
target: dependencies
     command

Note:
There must be a tab before command.
The makefile is usually named as makefile or Makefile

To create the makefile of previous program finapp1.c, the makefile is as follows:

#Creating Program
finapp1: finapp1.o myfinancial1.o
 gcc finapp1.o myfinancial1.o -lm -o finapp1

#Creating Objects
finapp1.o: finapp1.c myfinancial.h
 gcc -c finapp1.c -o finapp1.o

myfinancial1.o: myfinancial1.c myfinancial.h
 gcc -c myfinancial1.c -lm -o myfinancial1.o

clean:
 rm -f finapp1 finapp1.o myfinancial1.o

This is the more explicit way to instruct the make program how to compile the programs line by line. Please note that the final program must come first before compilation of object. It is a drill down approach.

After the make file is written, you can package all the program and makefile together.

To compile the program just type
make

To remove the compiled program and object type
make clean

However, we need not be so explicit because make program know how to compile programs. We can set the compile flags and the linking flags as follows:

CFLAGS=-Wall
LDFLAGS=-lm

#Creating Program
finapp1: finapp1.o myfinancial1.o myfinancial.h

clean:
 rm -f finapp1 finapp1.o myfinancial1.o

Note:
CFLAGS refers to complie flags
LDFLAGS refers to linking flags

By indicating our target program and the dependencies, the make program will compile the program and link them appropriately using the flags indicated. You need to supply finapp1.c, myfinancial1.c, myfinancial.h and makefile.

Since the functions object file need not be compiled every time, we can use the object file with the the main C program. The makefile is the same except that under clean section you don't remove the object file myfinancial1.o. You will be supplying myfinancial1.o instead of myfinancial1.c.

The makefile will be as follows:

CFLAGS=-Wall
LDFLAGS=-lm

#Creating Program
finapp1: finapp1.o myfinancial1.o myfinancial.h

clean:
 rm -f finapp1 finapp1.o 

To compile the program just type
make

To remove the compiled program and object type
make clean

*****

Wednesday, August 14, 2013

Create C Program with Shared Library (Dynamic Link Library) in Linux

Shared Library (Dynamic Link Library)

Shared library (a.k.a dynamic link library) is a library file that is called and linked by a dynamic linker during program execution time.

Naming Convention
In Linux, all shared library are name with a prefix lib and ends with .so. The actual file name of a shared library should follow the convention follow by a period and a version number, follow by a period and a minor version number follow by a period and a release number. Therefore a shared library file should be named as: libmymath.so.1.0.1.

Please note that you also need to create a so name file using the same file name but without the minor version and release number. Therefore a shared library file should be named as: libmymath.so.1.

You will also need a linker name using the file name as so name but without the version number. Therefore a shared library file should be named as: libmymath.so

A typical shared library should list as actual file, so name file and linker named file, as shown below:
libmymath.so.1.0.1
libmymath.so.1 -> libmymath.so.1.0.1
libmymath.so -> libmymath.so.1

Program Example
We will be creating a shared library file with the following headers and program.

The headers file named libmymath.h should contain the following:

#define PI 3.1415

double CircleArea (double radius);
double CircleCircumference (double radius);

double PowerOf2 (double number);
double PowerOf3 (double number);

The library program file libmymath1.c contains the following code:

#include "libmymath.h"

double CircleArea (double radius)
{
 return radius * radius * PI;
}

double CircleCircumference (double radius)
{
 return 2 * radius * PI;
}

The library program file libmymath2.c contains the following code:

#include "libmymath.h"

double PowerOf2 (double number)
{
 return number * number;
}

double PowerOf3 (double number)
{
 return number * number * number;
}

Compiling a Shared Library

In order to create a shared library, you need to compile the library program into a position independent code. The command to use is as follows:
gcc -fPIC -Wall -c -g libmymath1.c

This command create an object file libmymath1.o
-fPIC is to produce PIC(position independent code)
-g write debugging info into object file, this is optional but recommended

Use the same command to compile the second library program file libmymath2.c.

Create Library Files

Next, we need to create the library file named libmymath.so.1.0.1 with so name. The command is as follows:
gcc -shared -Wl,-soname,libmymath.so.1 -o libmymath.so.1.0.1 libmymath1.o libmymath2.o

Now, we need to configure the soname and create a soft link for libmymath.so.1. Use the following command:
ldconfig -n ./

Next, we need to create another soft link for the linker
ln -s libmymath.so.1 libmymath.so

Now we have 3 files as below:
libmymath.so.1.0.1
libmymath.so.1
libmymath.so

Distribution of Library Files

(Note: This section require user to use root privilege, use the command su)

According to the FHS (Filesystem Hierarchy Standard), it is recommended that most libraries should be installed in /usr/lib; libraries that are required for startup should be in /lib and libraries that are not part of the system should be in /usr/local/lib. If you are programming for Linux OS then your libraries should be either in /lib or /usr/lib. For application program it is recommend to install the libraries at /usr/local/lib.

For RedHat based system /usr/local/lib is not in the default search path. There are additional work involved. You either need to create a conf file or you can change the settings in /etc/ld.so.conf. The recommended method is to create a conf file as follows:
echo /usr/local/lib >> /etc/ld.so.conf.d/mylib.conf

Now, we can move library files to /usr/local/lib:
mv libmymath.so.1.0.1 libmymath.so.1 libmymath.so /usr/local/lib 

Finally, we need to run ldconfig to reload the cache. Every time when a new shared library is added, ldconfig must be run to recreate the symbolic link to the cache.
ldconfig

Note: Remember to use root privilege for all the commands in this section. Please note that cp command does not work when copying soft link to a new location. You can only copy the actual file.

Create Application Program

The application program that uses the shared library is listed below:

#include <stdio.h>
#include "libmymath.h"

int main ()
{
 double r = 4.0;
 double n = 5.0;

 printf ("Radius %.2f, area is %.2f \n", r, CircleArea(r));
 printf ("Radius %.2f, circumference is %.2f \n", r, CircleCircumference(r));
 printf ("%.2f to the power of 2 is %.2f \n", n, PowerOf2(n));
 printf ("%.2f to the power of 3 is %.2f \n", n, PowerOf3(n));

 return 0;
}

Compiling and Testing the Application

To compile the application, use the command:
gcc -Wall app1.c -o app1 -lmymath

Next we need to test if the application can locate the share library. Use the command ldd  as follows:
ldd app1

Note: Make sure under libmymath.so.1 is pointed to the correct file under /usr/local/lib. If you encounter this error "libmymath.so.1 => not found", this error indicates that the system could not find the library file. If you encounter such error, make sure that the default search path is properly configure especially for Fedora, CentOS and Red Hat system. You might need to run ldconfig again to refresh the cache.

BEWARE: DO NOT run ldd on program that you do not trust as it is possible for an untrusted program to force the ldd user to run arbitrary code.

Now, you can run the application as follows:
./app1

Note:
The most common error for using shared library is when the system could not locate the library file. Another common error happens when there are multiple versions of the library file.

Additional Tools
You can use the command nm to examine the library file and list the functions. Use nm -s -D lib<filename>.so.1.0.1 to list the functions in the library file:
nm -s -D libmymath.so.1.0.1


The instructions above is a simple guide to create a dynamic link library. Please note that the subject of software library management is a complex one. More research should be done for managing large and complex libraries.

***** 

Create C Program with Static Library in Linux

Consider the following C program:

#include <stdio.h>
#include <math.h>

double tvm (double rate, int terms, double principal);

int main ( )
{
 double myrate;
 int myterm;
 double myprincipal;
 double myreturn;

 printf ("Please enter the following:\n");
 printf ("Rate of return:(divide by 100, 4% is 0.04) ");
 scanf ("%lf", &myrate);
 printf ("\n");

 printf ("Number of terms:(No decimals): ");
 scanf ("%d", &myterm);
 printf ("\n");

 printf ("The principal amount: ");
 scanf ("%lf", &myprincipal);
 printf ("\n");

 myreturn = tvm (myrate, myterm, myprincipal);
 printf ("Your return after %d term is $%.2lf.\n", myterm, myreturn);

 return 0;
}

double tvm (double rate, int terms, double principal)
{
 double dn;
 double pp;
 dn = terms;

 pp = pow (1+rate, dn);
 return principal * pp;
} 

You can place the tvm (Time Value of Money) function into a static library so that you can reuse the function.

To create a static library, you need to place the function in mymath.c and create a separate header file mymath.h.

Note: You can have many C program file with just one header file such as lib.h, lib1.c, lib2.c ... and so on.

The header file mymath.h is as follows:

#include <math.h>

double tvm (double rate, int terms, double principal);

The program file for tvm function mymath1.c is as follows:

#include "mymath.h"

double tvm (double rate, int terms, double principal)
{
 double dn;
 double pp;
 dn = terms;

 pp = pow (1+rate, dn);
 return principal * pp;
} 

To compile the tvm fumction program use the command:
gcc -Wall -c mymath1.c 

-c stands for compile only
The compiler create an object file mymath1.o

Create Static Library

You can create static library using the command ar. This command also allows you to add additions library functions.

Library Naming Convention
The naming convention of a library package must be prefix with lib follow by the name of the library and the file must end with .a. Therefore a typical library should be named as libmymath.a. 

Common usage of ar command is as follows:
ar rcs libmymath.a mymath1.o

Options:
r - insert the object files to archive
c - create archive if not exist
s - create index

You can append additional object file to the library file as follows: 
ar rcs libmymath.a mymath2.o

Create the Application Program

Create the following application program named as app1.c:

#include <stdio.h>
#include "mymath.h"

int main ( )
{
 double myrate;
 int myterm;
 double myprincipal;
 double myreturn;

 printf ("Please enter the following:\n");
 printf ("Rate of return:(divide by 100, 4 percent is 0.04): ");
 scanf ("%lf", &myrate);
 printf ("\n");

 printf ("Number of terms:(No decimals): ");
 scanf ("%d", &myterm);
 printf ("\n");

 printf ("The principal amount: ");
 scanf ("%lf", &myprincipal);
 printf ("\n");

 myreturn = tvm (myrate, myterm, myprincipal);
 printf ("Your return after %d term is $%.2lf.\n", myterm, myreturn);

 return 0;
}

Note: Please note that you can use #include "mymath.h" or  #include "~/Documents/cprog/include/mymath.h", depending on where your header file is.

Compile The Application

If static library file and header file are in the same folder then use any of the following command:
gcc -Wall app1.c -o app1 -lm -lmymath -L ./
or
gcc -Wall app1.c -o app1 -lm libmymath.a

Options:
-l option follow by library name indicate which static library to link, note that this option automatically add prefix lib and append .a, If you have more than one library file you must indicate it separately.
-L locates the path of library

If your file libmymath.a is located in /usr/lib or /usr/local/lib (man ld to see search path) then you no need -L, you can just use
gcc -Wall app1.c -o app1 -lm -lmymath

If your library file and header file are located in separate folder then
gcc -Wall app1.c -o app1 -lm -lmymath -I ~/Documents/cprog/include/ -L ~/Documents/cprog/slib/

Additional Tools 

Besides gcc and ar, you can also use ranlib. Ranlib is equivalent to the command ar -s. There is also another tool known as ld. This is the basic linker which usually runs behind the scene when you run gcc, use man ld to see default search path for static library.

Library Display Tools
Another useful tool is nm. This tool display object files or library file. The command ar can also be use to display object file.

To check what is inside libmymath.a, use the command:
ar t libmymath.a 

Note: The results will be a list of object files <filename>.o

Alternatively, you can use the following command: 
nm -s libmymath.a

Note: This is the better tools because besides object files it also list the function names. 

Special Notes:

Do we need to create a library file?
When you use the command ar to create a library file, it is basically an archive of many object files. A library file is useful for packaging and distribution purpose.

You can always compile your program without library file and use object files. The above program can be compile as follows:
gcc -Wall app1.c mymath1.o -o app1 -lm

As you create more and more object files, then it is easier to group all the similar object files into a single library file. It is easier to use library file to distribute to other software developers instead of multiple object files.



*****

Tuesday, August 13, 2013

Create C Program with Dynamic Link Library (DLL) using Command Line (Implicit Link) in Windows

The following procedure is to create a C program with a dynamic link library using Developer Command Prompt for VS2012.

Brief Introduction to Dynamic Link Library (DLL)
The important difference between DLL and static library is that the code of external function is stored in the DLL file, whereas when linking with static library, the code of the external functions is copied to the execution file of the application program. With static library, you just need an execution file whereas with DLL you need both the execution file and the DLL file for the program to work.

Implicit or Explicit Link
When creating DLL, we have the choice of implicit linking or explicit linking. Since implicit linking is easier and common, this article will focus on implicit linking. For additional information please refer to the following:

Linking Implicitly
Linking Explicitly
Determining Which Linking Method to Use

Examples:
The following example is a normal C program with functions. 

#include <stdio.h>
#define PI 3.1415

double PowerOf2 (double UserNumber);
double PowerOf3 (double UserNumber);
double CircleArea (double UserRadius);
double CircleCircum (double UserRadius);

int main ( )
{

 double p2 = 10.0;
 double p3 = 5.0;
 double radius = 4.0;

 printf ("The number %.2f to the power of 2 is %.2f. \n", p2, PowerOf2(p2));

 printf ("The number %.2f to the power of 3 is %.2f. \n", p3, PowerOf3(p3));

 printf ("A circle with a radius of %.2f, the area is %.2f. \n", radius, CircleArea(radius));

 printf ("A circle with a radius of %.2f, the circumference is %.2f. \n", radius, CircleCircum(radius));

 return 0;

}

double PowerOf2 (double UserNumber)
{
 return UserNumber * UserNumber;
}


double PowerOf3 (double UserNumber)
{
 return UserNumber * UserNumber * UserNumber;
}

double CircleArea (double UserRadius)
{
 return UserRadius * UserRadius * PI;
}
 
double CircleCircum (double UserRadius)
{
 return 2 * UserRadius * PI;
}

We will use the above example to create a dynamic link library and an application program that use this library. We will place the DLL in a shared public folder and place the application in the personal document folder.


To create Dynamic Link Library
To create a dynamic link library, it consist of 2 files MyCMathDll.h and MyCMathDll.c

Step 1: Create a header file for DLL
Open a notepad  and create the headers of the DLL as follows. Named the file as MyCMathDll.h

Important: Please make sure that you save the file in program.c instead of program.c.txt. Notepad save everything in .txt extension by default. To avoid this problem, under the file explorer select Organize >> Folder and search option, select the view tab and clear the check on "Hide  extensions for known file types".

Add the following to the headers:

#ifdef MYCMATHDLL_EXPORTS
#define MYCMATHDLL_API __declspec(dllexport) 
#else
#define MYCMATHDLL_API __declspec(dllimport) 
#endif

#define PI 3.1415

MYCMATHDLL_API double PowerOf2 (double UserNumber);
MYCMATHDLL_API double PowerOf3 (double UserNumber);
MYCMATHDLL_API double CircleArea (double UserRadius);
MYCMATHDLL_API double CircleCircum (double UserRadius);

The dllexport and dllimport attributes are extensions to the C and C++. You can use them to export and import functions to or from a DLL. When the MYCMATHDLL_EXPORTS symbol is defined, the MYCMATHDLL_API symbol will set the __declspec(dllexport) modifier in the member function declarations. This enables the function to be exported by the DLL so that it can be used by other applications. When MYCMATHDLL_EXPORTS is undefined, MYCMATHDLL_API defines the __declspec(dllimport) modifier in the member function declarations. This enables the compiler to optimize the importing of the function from the DLL for use in other applications. Using command line, you need to use /D option to define MYCMATHDLL_EXPORTS during compilation.

You can also define the header file this way.

#define PI 3.1415

__declspec(dllexport) double PowerOf2 (double UserNumber);
__declspec(dllexport) PowerOf3 (double UserNumber);
__declspec(dllexport) CircleArea (double UserRadius);
__declspec(dllexport) double CircleCircum (double UserRadius);

For further information on dllexport and dllimport please refer to this article.


Step 2: Create the source code for the functions
Open a notepad  and create the source code of the DLL as follows. Named the file as MyCMathDll.c

#include "MyCMathDll.h"

double PowerOf2 (double UserNumber)
{
 return UserNumber * UserNumber;
}


double PowerOf3 (double UserNumber)
{
 return UserNumber * UserNumber * UserNumber;
}

double CircleArea (double UserRadius)
{
 return UserRadius * UserRadius * PI;
}
 
double CircleCircum (double UserRadius)
{
 return 2 * UserRadius * PI;
}


Step 3: Compile and create the DLL
Open the Developer Command Prompt for VS2012. Use the  option /LD to generate DLL file. If you have included the pre-processor MYCMATHDLL_EXPORTS, use /D option. The command is as follows: 

cl /DMYCMATHDLL_EXPORTS MyCMathDll.c /LD 


Debug any error for compilation error. The compiler should generate an object file, an export file, a library (lib) file named MyCMathDll.lib and a DLL file named MyCMathDll.dll.

If you use the following for headers:

__declspec(dllexport) double PowerOf2 (double UserNumber);

Then the compilation command will be 

cl MyCMathDll.c /LD 





Create a C Application Program Using DLL

Step 1: Create an application program
Open a notepad and create the application program making use of the functions in the DLL as listed below. Named the file as MyApp3.c. Save the file in your personal folder.

Please note that you must know the location of the header file. You need to indicate the header file name and extension if the header file is in the same folder as this program. Otherwise you need to specify the full path in the program or alternatively you could specify the include path during compilation time. The latter method is much preferred because you don't need to change the program when the header file relocate.

#include <stdio.h>
#include "MyCMathDll.h"

int main ( )
{

   double p2 = 10.0;
   double p3 = 5.0;
   double radius = 4.0;

   printf ("The number %.2f to the power of 2 is %.2f. \n", p2, PowerOf2(p2));

   printf ("The number %.2f to the power of 3 is %.2f. \n", p3, PowerOf3(p3));

   printf ("A circle with a radius of %.2f, the area is %.2f. \n", radius, CircleArea(radius));

   printf ("A circle with a radius of %.2f, the circumference is %.2f. \n", radius, CircleCircum(radius));

 return 0;

}

Step 2: Compile the program
Before compilation, you must know the full path of the lib file MyCMathDll.lib. If you did not specify the full path of your header file MyCMathDll.h you need to use /I option to indicate the search path for the headers file. 

cl MyApp3.c /I C:\Users\Public\Documents\MyCMathDll\ C:\Users\Public\Documents\MyCMathDll\MyCMathDll.lib 


If your program include the full path of the header file as shown below:

#include <stdio.h>
#include "C:\Users\Public\Documents\MyCMathDll\MyCMathDll.h"

// The rest of the program....

}

Then, the command for compilation is simpler:

cl MyApp3.c C:\Users\Public\Documents\MyCMathDll\MyCMathDll.lib 


Step 3: Run the program
Test the program using normal command prompt as shown



If I run my program from my personal folder, I encounter this error because the system could not locate the DLL file.

Please note that for the successful execution of the program. MyApp3.exe and MyCMathDll.dll should be in the same folder. Alternatively, the MyCMathDll.dll should be located where the Windows system could find. The search path the DLL files for Windows are as follows:
  1. The directory where the exe file is located.
  2. The Windows system directory. 
  3. The Windows directory. 
  4. The directories listed in the PATH environment variable.
To rectify the problem above I need to copy MyCMathDll.dll to the folder containing the exe file.

It is not advisable to place the DLL file in system folder or windows folder. For larger software firms that produces many software products, it is the common practice to place the commonly shared dll files under Program Files >> Common Files

This completes the procedure for creating a DLL in C using command line. Please note that the procedure for creating similar DLL using Visual Studio IDE is different





*****


Create C Program with Dynamic Link Library (DLL) using Visual Studio 2012 (Implicit Link)

The following procedure is to create a C program with a dynamic link library using Microsoft Visual Studio Express 2012.

Brief Introduction to Dynamic Link Library (DLL)
The important difference between DLL and static library is that the code of external function is stored in the DLL file, whereas when linking with static library, the code of the external functions is copied to the execution file of the application program. With static library, you just need an execution file whereas with DLL you need both the execution file and the DLL file for the program to work.

Implicit or Explicit Link
When creating DLL, we have the choice of implicit linking or explicit linking. Since implicit linking is easier and common, this article will focus on implicit linking. For additional information please refer to the following:

Linking Implicitly
Linking Explicitly
Determining Which Linking Method to Use

Examples:
The following example is a normal C program with functions without using any custom static library. 

#include <stdio.h>
#define PI 3.1415

double PowerOf2 (double UserNumber);
double PowerOf3 (double UserNumber);
double CircleArea (double UserRadius);
double CircleCircum (double UserRadius);

int main ( )
{

 double p2 = 10.0;
 double p3 = 5.0;
 double radius = 4.0;

 printf ("The number %.2f to the power of 2 is %.2f. \n", p2, PowerOf2(p2));

 printf ("The number %.2f to the power of 3 is %.2f. \n", p3, PowerOf3(p3));

 printf ("A circle with a radius of %.2f, the area is %.2f. \n", radius, CircleArea(radius));

 printf ("A circle with a radius of %.2f, the circumference is %.2f. \n", radius, CircleCircum(radius));

 return 0;

}

double PowerOf2 (double UserNumber)
{
 return UserNumber * UserNumber;
}


double PowerOf3 (double UserNumber)
{
 return UserNumber * UserNumber * UserNumber;
}

double CircleArea (double UserRadius)
{
 return UserRadius * UserRadius * PI;
}
 
double CircleCircum (double UserRadius)
{
 return 2 * UserRadius * PI;
}

We will use the above example to create a dynamic link library and an application program that use this library. We will place the DLL in a shared public folder and place the application in the personal document folder.

To create a dynamic link library, it consist of 2 files MyMathDll.h and MyMathDll.c

To create Dynamic Link Library
Step 1: Create a new project as dynamic link library
Create a new project using MyMathDll as project name


Click "OK". Then click "Next". On following screen you need to specify that you are creating a DLL and make sure you check Empty project.


Step 2: Create the headers file
Under Solution Explorer, right click Headers Files >> Add >> New Item as shown below.


Select header file as file type and rename the header file to MyMathDll.h


Click "Add".

Add the following to the headers:

#ifdef MYMATHDLL_EXPORTS
#define MYMATHDLL_API __declspec(dllexport) 
#else
#define MYMATHDLL_API __declspec(dllimport) 
#endif

#define PI 3.1415

MYMATHDLL_API double PowerOf2 (double UserNumber);
MYMATHDLL_API double PowerOf3 (double UserNumber);
MYMATHDLL_API double CircleArea (double UserRadius);
MYMATHDLL_API double CircleCircum (double UserRadius);

The dllexport and dllimport attributes are extensions to the C and C++. You can use them to export and import functions to or from a DLL. When the MYMATHDLL_EXPORTS symbol is defined, the MYMATHDLL_API symbol will set the __declspec(dllexport) modifier in the member function declarations. This enables the function to be exported by the DLL so that it can be used by other applications. When MYMATHDLL_EXPORTS is undefined, MYMATHDLL_API defines the __declspec(dllimport) modifier in the member function declarations. This enables the compiler to optimize the importing of the function from the DLL for use in other applications. By default, MYMATHDLL_EXPORTS is defined when the MyMathDll project is built.

You can also define the header file this way.

#define PI 3.1415

__declspec(dllexport) double PowerOf2 (double UserNumber);
__declspec(dllexport) PowerOf3 (double UserNumber);
__declspec(dllexport) CircleArea (double UserRadius);
__declspec(dllexport) double CircleCircum (double UserRadius);

For further information on dllexport and dllimport please refer to this article.

Step 3: Create the Implementation Program
Under Solution Explorer, right click Source Files >> Add >> New Item. Rename the program to MyMathDll.c.


Enter the source code as follows

#include "MyMathDll.h"

double PowerOf2 (double UserNumber)
{
 return UserNumber * UserNumber;
}

double PowerOf3 (double UserNumber)
{
 return UserNumber * UserNumber * UserNumber;
}

double CircleArea (double UserRadius)
{
 return UserRadius * UserRadius * PI;
}
 
double CircleCircum (double UserRadius)
{
 return 2 * UserRadius * PI;
}

Step 4: Build solutions
Build solutions. You should have result as follows:


Once the compilation is complete, close the project.


Create a C Application Program Using DLL
Step 1: Create a new project
Create a new project using the name MyApp3 with Console Application as options. Remember to clear all headers and checked Empty Project.

Step 2: Establish Link with the Static Library
Under Solution Explorer, right click and select Add >> Existing Projects


Navigate to the project folders of MyMathDll and select the project file MyMathDll.vcxproj and click Open.

Your solution explorer should show two projects like below:


Select MyApp3, right click and select properties. Under Common Properties, select Framework and References. Click "Add New Reference"


You should see the following screen, there should be a project named "MyMathDll". Check the project as shown below and click "OK".


On the properties page, under Configuration Properties >> C/C++ expand the list in C/C++ and select "General" as shown below.


For first line "Additional Include Directories", click the arrow and select edit. The following dialog box shows:


Click the "New Line" icon and click on the button "...". Now you need to navigate to the DLL folder. Do not select the folder "MyMathDll" under Projects, drill one level down and select the folder "MyMathDll". The purpose is to the select the folder that contain the header file. Highlight the folder and click Select Folder.


Click OK. Then click Apply. You can close the property dialog box.

Step 3: Create the application program 
Under Solution Explorer, right click Source Files >> Add >> New Item. Rename the program to MyApp3.c.

Enter the following program:

#include <stdio.h>
#include "MyMathDll.h"

int main ( )
{

 double p2 = 10.0;
 double p3 = 5.0;
 double radius = 4.0;

 printf ("The number %.2f to the power of 2 is %.2f. \n", p2, PowerOf2(p2));

 printf ("The number %.2f to the power of 3 is %.2f. \n", p3, PowerOf3(p3));

 printf ("A circle with a radius of %.2f, the area is %.2f. \n", radius, CircleArea(radius));

 printf ("A circle with a radius of %.2f, the circumference is %.2f. \n", radius, CircleCircum(radius));

 return 0;

}

Step 4: Build the solution.
After you have built the solutions, you should received a message similar to the one below. Please note that two projects are being built.


Step 5: Run the program
You can test the project from the command prompt as shown below:



Additional Note:
Please note that for the successful execution of the program. MyApp3.exe and MyMathDll.dll should be in the same folder. Alternatively, the MyMathDll.dll should be located where the Windows system could find. The search path the DLL files for Windows are as follows:

  1. The directory where the exe file is located.
  2. The Windows system directory. 
  3. The Windows directory. 
  4. The directories listed in the PATH environment variable.


This completes the procedure for creating a DLL in C using Visual Studio Express 2012. Please note that the procedure for creating similar DLL using command line is different from using the IDE. 







*****



Monday, August 12, 2013

Create C Program with Static Library using Command Line in Windows

The following procedure is to create C program with static library using Microsoft Visual Studio Express 2012 command prompt. For brief introduction to software library, please refer to the previous post Create C Program with Static Library using Visual Studio. Click here for procedure of creating a C program using Visual Studio.

Example:
The following example is a normal C program with functions without using any custom static library. 

#include <stdio.h>
#define PI 3.1415;

double PowerOf2 (double UserNumber);
double PowerOf3 (double UserNumber);
double CircleArea (double UserRadius);
double CircleCircum (double UserRadius);

int main ( )
{

 double p2 = 10.0;
 double p3 = 5.0;
 double radius = 4.0;

 printf ("The number %.2f to the power of 2 is %.2f. \n", p2, PowerOf2(p2));

 printf ("The number %.2f to the power of 3 is %.2f. \n", p3, PowerOf3(p3));

 printf ("A circle with a radius of %.2f, the area is %.2f. \n", radius, CircleArea(radius));

 printf ("A circle with a radius of %.2f, the circumference is %.2f. \n", radius, CircleCircum(radius));

 return 0;

}

double PowerOf2 (double UserNumber)
{
 return UserNumber * UserNumber;
}


double PowerOf3 (double UserNumber)
{
 return UserNumber * UserNumber * UserNumber;
}

double CircleArea (double UserRadius)
{
 return UserRadius * UserRadius * PI;
}
 
double CircleCircum (double UserRadius)
{
 return 2 * UserRadius * PI;
}

We will use the above example to create a static library and an application program that use this library. We will place the static library in a shared public folder and place the application in the personal document folder.

Create Static Library

Step 1: Create headers file for static library
Open a notepad  and create the headers of the static library as follows. Named the file as MyCMathLib.h

#define PI 3.1415;

double PowerOf2 (double UserNumber);
double PowerOf3 (double UserNumber);
double CircleArea (double UserRadius);
double CircleCircum (double UserRadius);


Important: Please make sure that you save the file in program.c instead of program.c.txt. Notepad save everything in .txt extension by default. To avoid this problem, under the file explorer select Organize >> Folder and search option, select the view tab and clear the check on "Hide  extensions for known file types".

Step 2: Create the source code for the functions
Open a notepad  and create the source of the static library as follows. Named the file as MyCMathLib.c.

#include "MyCMathLib.h"

double PowerOf2 (double UserNumber)
{
 return UserNumber * UserNumber;
}


double PowerOf3 (double UserNumber)
{
 return UserNumber * UserNumber * UserNumber;
}

double CircleArea (double UserRadius)
{
 return UserRadius * UserRadius * PI;
}
 
double CircleCircum (double UserRadius)
{
 return 2 * UserRadius * PI;
}


Step 3: Compile and create the static library
Open the "Developer Command Prompt for VS2012". Use the following command to compile without linking the library.

cl /c MyCMathLib.c 


Debug any error for compilation error. The compiler should generate an object file named MyCMathLib.obj

Next, use the following command to create the static library.

lib MyCMathLib.obj 


The compiler will generate the static library named as MyCMathLib.lib


Create Application Program using Static Library

Step 1: Create an application program
Open a notepad and create the application program making use of the functions in the static library as follows: Named the file as MyApp2.c. Save the file in your personal folder.

Please note that you must know the location of the header file. You need to indicate the header file name and extension if the header file is in the same folder as this program. Otherwise you need to specify the full path in the program or alternatively you could specify the include path during compilation time. The latter method is much preferred becasue you don't need to change the program when the header file relocates.

#include <stdio.h>
#include "MyCMathLib.h"

int main ( )
{

   double p2 = 10.0;
   double p3 = 5.0;
   double radius = 4.0;

   printf ("The number %.2f to the power of 2 is %.2f. \n", p2, PowerOf2(p2));

   printf ("The number %.2f to the power of 3 is %.2f. \n", p3, PowerOf3(p3));

   printf ("A circle with a radius of %.2f, the area is %.2f. \n", radius, CircleArea(radius));

   printf ("A circle with a radius of %.2f, the circumference is %.2f. \n", radius, CircleCircum(radius));

 return 0;

}

Step 2: Compile the program
Before compilation, you must know where the location of the static library (lib file). You need the full path for compilation.

cl MyApp2.c /I C:\Users\Public\Documents\MyCMathLib\ C:\Users\Public\Documents\MyCMathLib\MyCMathLib.lib 


If your program do not specify the full path for the header file, then you need to use the following command with /I option to include the directory for the search path.

If your program include the full path of the header file as shown below:

#include <stdio.h>
#include "C:\Users\Public\Documents\MyCMathLib\MyCMathLib.h"

// The rest of the program....

}
Then, the command for compilation is:

cl MyApp2.c /I C:\Users\Public\Documents\MyCMathLib\MyCMathLib.lib 


Step 3: Run the program
Test the program using normal command prompt as shown



Please note that you can place the execution file anywhere and run them because all the code in the static library is copied to the exe file while linking.

Please refer to the following post for:

For C programming in other platform please refer to the C Programming page.


*****

Create C Program with Static Library using Visual Studio 2012

The following procedure is to write and compile C program with a static library using Microsoft Visual Studio 2012 Express edition. For instruction on creating a basic C program using Visual Studio, please refer to the document here.

Brief Introduction to Software Library
A software library is a collections of previously written functions or program which can be reused. A C program always includes a  standard file called stdio.h. This file is the header file that describe all the pre-written function such as printf that comes with the compiler. This library file is also known as the system library. Library file that are created by users are called custom library.

There are two types of library, static library and dynamic link library. Both library files can share their codes and function with other program. A program that link with a static library will include all the program required during compilation time. After which you can ship the execution (exe) program to the user. Any changes in the static library means that you need to re-compile the program and ship to the user again.

For dynamic link library (DLL) the program of external functions are not included with the applications. Both dynamic link library (DLL) file and execution file (exe) must be shipped together. If there is any changes to the library, you just need to recreate the DLL file and ship the new library file to the user without any changes to the main execution program.


Examples:
In this exercise, we are going to create a program that includes some math function.
A normal program is as follows:

#include <stdio.h>
#define PI 3.1415;

double PowerOf2 (double UserNumber);
double PowerOf3 (double UserNumber);
double CircleArea (double UserRadius);
double CircleCircum (double UserRadius);

int main ( )
{

 double p2 = 10.0;
 double p3 = 5.0;
 double radius = 4.0;

 printf ("The number %.2f to the power of 2 is %.2f. \n", p2, PowerOf2(p2));

 printf ("The number %.2f to the power of 3 is %.2f. \n", p3, PowerOf3(p3));

 printf ("A circle with a radius of %.2f, the area is %.2f. \n", radius, CircleArea(radius));

 printf ("A circle with a radius of %.2f, the circumference is %.2f. \n", radius, CircleCircum(radius));

 return 0;

}

double PowerOf2 (double UserNumber)
{
 return UserNumber * UserNumber;
}


double PowerOf3 (double UserNumber)
{
 return UserNumber * UserNumber * UserNumber;
}

double CircleArea (double UserRadius)
{
 return UserRadius * UserRadius * PI;
}
 
double CircleCircum (double UserRadius)
{
 return 2 * UserRadius * PI;
}

Compile the above program to see if it works. For instruction on how to create a C program using MS Visual Studio 2012 Express, please refer to the article here.

To create a static library, we need to split the program into 2 parts. The main program and the static library which contain the functions. The static library will consist of 2 files MyMathLib.h and MyMathLib.c.

To create Static Library
Step 1: Create a new project as static library
Create a new project using MyMathLib as project name


Click "OK". Then click "Next". On following screen you need to specify that you are creating a static library.


Step 2: Create the headers file
Under Solution Explorer, right click Headers Files >> Add >> New Item as shown below.


Select header file as file type and rename the header file to MyMathLib.h


Click "Add".

Add the following to the headers:

#define PI 3.1415;

double PowerOf2 (double UserNumber);
double PowerOf3 (double UserNumber);
double CircleArea (double UserRadius);
double CircleCircum (double UserRadius);


Step 3: Create the Implementation Program
Under Solution Explorer, right click Source Files >> Add >> New Item. Rename the program to MyMathLib.c.


Enter the source code as follows

#include "MyMathLib.h"

double PowerOf2 (double UserNumber)
{
 return UserNumber * UserNumber;
}

double PowerOf3 (double UserNumber)
{
 return UserNumber * UserNumber * UserNumber;
}

double CircleArea (double UserRadius)
{
 return UserRadius * UserRadius * PI;
}
 
double CircleCircum (double UserRadius)
{
 return 2 * UserRadius * PI;
}

Step 4: Build solutions
Build solutions. Once the compilation is complete, close the project.

Create a C Application Program Using the Static Library
Step 1: Create a new project
Create a new project using the name MyApps1 with Console Application as options. Remember to clear all headers and checked Empty Project.

Step 2: Establish Link with the Static Library
Under Solution Explorer, right click and select Add >> Existing Projects


Navigate to the project folders of MyMathLib and select the project file MyMathLib.vcxproj

Your solution explorer should show two projects like below:


Select MyApps1, right click and select properties. Under Common Properties, select Framework and References. Click "Add New Reference"


You should see the following screen, there should be a project named "MyMathLib". Check the project as shown below and click "OK".


On the properties page, under Configuration Properties >> C/C++ expand the list in C/C++ and select "General" as shown below.


For first line "Additional Include Directories", click the arrow and select edit. The following dialog box shows:


Click the "New Line" icon and click on the buttion "...". Now you need to navigate to the static library folder. Do not select the folder "MyMathLib" under Projects, drill one level down and select the folder "MyMathLib". Highlight the folder and click select folder.


Click "OK". Then click "Apply". You can close the property dialog box.

Step 3: Create the application program 
Under Solution Explorer, right click Source Files >> Add >> New Item. Rename the program to MyApps1.c.

Enter the following program:

#include <stdio.h>
#include "MyMathLib.h"

int main ( )
{

 double p2 = 10.0;
 double radius = 4.0;

 printf ("The number %.2f to the power of 2 is %.2f. \n", p2, PowerOf2(p2));

 printf ("A circle with a radius of %.2f, the area is %.2f. \n", radius, CircleArea(radius));

 return 0;

}

Step 4: Build the solution.
After you have built the solutions, you should received a message similar to the one below. Please note that two projects are being built.


Step 5: Run the program
You can test the project from the command prompt as shown below:



Note:
This completes the procedure for creating a static library in C using Visual Studio Express 2012.

Please note that the procedure for creating similar static library using command line is different from using the IDE. 


Please refer to the following post for:

For C programming in other platform please refer to the C Programming page.

*****

Compiling C Program in Linux Part 1

Most of Linux are written in C. To compile C program we need a minimum of the follow packages:

  • Gcc – the compiler for C program
  • Glibc – contains standard C libraries
  • Glibc-devel – contain standard headers file
  • Binutils – contains various utilities such as assembler and linker


Writing C Program
You can use many tools in write C code. The most popular tool is vim and gedit. Listed below is a list of tools.

GUI (Graphic User Interface) Editing Tools

  • gedit
  • geany
  • Eclipse


Command Line Editing Tools

  • vim
  • vi
  • Emacs


A Simple C Program
Listed below is a simple C program called sick.c

#include <stdio.h>
int main()
{
     printf ("Sick of printing hello world!\n");
     return 0;
}

To compile the program
$gcc -Wall sick.c -o verysick

The option -Wall display all possible warning (-W is for warning and all is to display all possible warnings) and -o indicate to the compiler that user want the output to be name after the -o option.

To run the program indicate the complete path or
$./verysick


Below is a more complex C program called tvm.c
#include <stdio.h>
#include <math.h>

double tvm (double rate, int terms, double principal);

int main ( )
{
 double myrate;
 int myterm;
 double myprincipal;
 double myreturn;

 printf ("Please enter the following:\n");
 printf ("Rate of return: ");
 scanf ("%lf", &myrate);
 printf ("\n");

 printf ("Number of terms:(No decimals): ");
 scanf ("%d", &myterm);
 printf ("\n");

 printf ("The principal amount: ");
 scanf ("%lf", &myprincipal);
 printf ("\n");

 myreturn = tvm (myrate, myterm, myprincipal);
 printf ("Your return after %d term is $%.2lf.\n", myterm, myreturn);

 return 0;
}

double tvm (double rate, int terms, double principal)
{
 double dn;
 double pp;
 dn = terms;

 pp = pow (1+rate, dn);
 return principal * pp;
} 


To compile the program
$gcc -Wall tvm.c -lm -o tvm

The additional option -lm is required so that the compiler will search for the math library in reference to including math.h. -l is the option for library. The math library is libm.a. You can omit the prefix lib and .a.

To run the program indicate the complete path or
$./tvm 


*****