Function Prototypes in C
Archive - Originally posted on "The Horse's Mouth" - 2010-01-11 23:09:43 - Graham EllisPrograms other than the shortest are name up of named blocks of code (functions) into which parameters are passed and from which results are returned. And rather than have all the functions that make up an application in one file of source, you'll share them between several. That way, maintainable is in more manageable chunks, and you can use parts of your code in several programs by loading the same named blocks into a series of programs that share them.
But there's a bit of an "issue" with that, in that at the time you compile each of the individual files of functions (prior to loading them *all* together), you're in danger of calling a function with the wrong number and type of parameters, and to not be "picked up" on the error by the compiler either. If you've even seen "Segmentation fault - memory violation" messages from a program, there's a good chance that they were caused by an error of this type that wasn't checked. Kernighan and Ritchie, two of the originators of C, wrote the definitive text book on the language and this version of the language is known as "K&R C".
Under more recent C - "ANSI C" - there's a solution. At the top of each file of your C source, you should include a function prototype - a template, if you like - for each function that you'll call, so that the compiler CAN make its checks, and segmentation faults / segmentation violations can be largely pre-empted.
Here are some sample function prototypes:
float gimme_table(float, int );
void silly_message() ;
The gimme_table function takes two parameters - a float and an int, and returns a float. silly_message may or may not take parameters (use the word void in the brackets to say it never takes any parameters) and returns nothing.
So far so good ... but do you REALLY want to repeat all the function prototypes in every file of source - if you do, you have just created a maintenance problem. So you group them all together into a file which you load through a #include directive to your C preprocessor.
By default the ANSI C compiler will complain strongly about missing function prototypes ... so that you've now got a scheme in which you maintain a single file that lists all your functions, and which will tell you straight away at compile time if you've accidentally created some code which doesn't match what you have set up, rather than having to find out about it when debugging some obscure behavior much later on.
There's a complete example - all three files - on our web site; a new example written earlier today on the C Programming course
1. The main program
2. The functions that it uses
3. The file of function prototypes that's called in by both of the other two.