Guides:C/C Crash Course/Writing functions and Libraries

From CoderGuide

Jump to: navigation, search

Back to TOC

Writing your own function libraries

This topic is divided into four sections:

Introduction

Now that we've gotten this far, you're probably wanting to write your own software library: a collection of functions for you to use, and reuse in your programs. After all, who wants to keep typing in the same code over and over again for use in their programs? Remember that sgets() function we wrote? Wouldn't you like to reuse that function in your programs without having to type the code, and function prototype, over again if you want to use it in your own programs? Well, writing your own software libraries lets you do that.

Writing software libraries makes your life a lot easier as a program, and can make your code look cleaner by putting useful functions, or class of functions, into their own files. Even better, there isn't much extra you need to know to write your own!

To write your own software library, you need to write two files: one is the header file (those ".h" files we've been including in our programs) and a source file (the ".c" files we've been writing and, up until this point, all contained a function main()). Since function libraries are to be linked to another program, like the standard libraries, you do not write a main() function. Header files contain the function prototypes, and other definitions required by your library. It's also a good idea to describe how to use the functions in your library at the top of your library file for quick reference later. You must include this file in both your library source code, and in the source code of the program that is to use your library.

Personal tools