Appendix C. Libraries

 

In chapter 4 we covered software libraries and how they’re used to extend the basic functionality of the Arduino. Other chapters have provided examples of how using libraries in your own projects can easily extend their functionality.

When you’ve gained some experience in writing your own sketches there will come a time when you develop a sketch that you could reuse in future projects or that may be useful to the Arduino community. You can either keep the developed code in a sketch or split it out into a library. Splitting the sketch out into a library will probably make it more useful to other users.

This appendix will guide you through the anatomy of a library so that you can see what’s involved in writing your own.

C.1. Anatomy of a library

Arduino sketches are coded using C++ (see appendix B for more detail), and much of the complexity and functionality of Arduino programming is hidden from users by the extensive use of software libraries.

A software library is made up of at least one C++ class and maybe many more. A class consists of two files: a header file with a .h extension and a file with a .cpp extension.

The .h (header) file acts as a blueprint for the library, describing the functions of the library and what the class does. The .cpp file contains the fine detail of the library, detailing the functions and variables declared by the header.

Let’s start by looking at the makeup of a header file.

C.1.1. The .h (header) file

C.2. Using a library