A bit of details about header files, its similar to that of interface in java. Basically, its part of an object oriented concept that allows you to separate your program logic from other developers, the purpose really, is to allow other developers to know input and output information about your program (nothing much about the internal program logic) so as to allow other developers to develop their own program independently while you write your part.
Consider the following example:
We are trying to create a calculator program, we have a few programmers working on different components, one of which is multiplication. While developing the main calculator program (calculator.c), someone else can work on multiplication program logic (Multiplication.c). In a Multiplication there is an input of integer and and output of integer. Therefore, we can create a Multiplication.h file that specifies the method that the main calculator program developer should call in order to get the multiplied value of an input.
These are the files that forms the story above,
Multiplication.c
#include <stdio>
#include "Multiplication.h"
int getMultiply(int var1, int var2) {
return var1 * var2;
}
Multiplication.h
int getMultiply(int var1, int var2);
Calculator.c
#include <stdio>
#include "Multiplication.h"
int main() {
printf ("Result of 2 x 2: %d", getMultiply(2,2));
return 0;
}
As we can see clearly above, the method getMultiply inside Multiplication.h does not include any details of the internal logic of the multiplication method. To use a custom header, you have to include it within the main program as shown in line 2 of Calculator.c and call it as if the method is local within the program.
How do we actually compile the program?
1. compile the header's c files (not the header file):
gcc -c Multiplication.c
You can use the -c option with gcc to create the corresponding object (.o) file from a .c file. By specifying -c, the compiler will stop after the assembler stage, you will see that the output will be Multiplication.o.
2. compile the main program
gcc -o Calculator Calculator.c Multiplication.o
Here we specified the output to be called Calculator and we specified the input file of Multiplication.o which we generated from step1.
3. we can now run the program using:
./Calculator
If the program does not execute, and throws a permission error, try "chmod 755 Calculator"
Right. That's all folks.
I found a good lecture after posting this!
http://www.eng.hawaii.edu/Tutor/Make/1-4.html
No comments:
Post a Comment