C Function Libraries
An example of the conventional organization of a function library into .h (header) and .c (source) files.
Main.c
#include <stdio.h>
#include <stdlib.h>
#include "AlphabetLib.h"
int main(void) {
char someLetter = 'F';
int value = letterValue(someLetter);
printf("Letter %c is the %d letter of the alphabet.\n", someLetter, value);
int n = 13;
char c = valueLetter(n, 0);
printf("The letter that is %d in the alphabet is %c.\n", n, c);
return 0;
}
AlphabetLib.h
#ifndef ALPHABETLIB_H_
#define ALPHABETLIB_H_
/**
* Returns a value corresponding to the
* alphabetical order of the letter.
* e.g. c = 3.
* Not case sensitive.
**/
int letterValue(char letter);
/**
* Returns the letter corresponding to the
* alphabetical order of the value.
* e.g. 4 = D.
* Returns upper case if uppercase != 0;
**/
char valueLetter(int value, int uppercase);
#endif /* ALPHABETLIB_H_ */
AlphabetLib.c
#include "AlphabetLib.h"
int letterValue(char letter){
if (letter > 64 && letter < 91){
return letter - 64;
}
if (letter > 96 && letter < 123){
return letter - 96;
}
return -1;
}
char valueLetter(int value, int uppercase){
if (value > 0 && value < 27){
if (uppercase){
return value + 64;
} else {
return value + 96;
}
}
return '?';
}