Maketober Day 24: Make a C++ class library for Arduino

robsSettings.png

Once you’ve written a bit of code you start to come up with libraries that you’d like to reuse in other projects. They might be things like drivers for particular pieces of hardware or useful storage or menu routines. If you are writing C++ code for your Arduino it turns out to be very easy to create library files. The Arduino development environment builds on what the C++ language uses to manage libraries.

It all hinges around the “library” folder in your Arduino installation. This is usually placed in the Arduino folder in your documents folder (as you can see above). You can also see that I’ve got lots of existing libraries. Every time I’ve downloaded a library it has ended up here. There is also a library file called Robs_Settings. That’s one that I made myself. If you have a look in this folder you will find the C++ source files that make it work:

settingfiles.png

For each library I have a .h file that contains definitions of the behaviours and a .cpp file that contains code. The idea is that a program that wants to use the library features will include the .h file so that it knows how to call the behaviours in the library. Then, when the program is built the compiler will find the .cpp file, compile the actual code and then all the different components will be linked together. When you start the compiler running you can tell it where to look for library files.

The Arduino environment knows the location of the library folder and will scan this folder when you open the “Include Library” option in the Sketch menu. It will show you any libraries that you have downloaded along with the one that we’ve just created.

arduino include.png

When I include the Robs_Settings library the Arduino environment scans the library folder and creates an include statement for each of the .h files that it finds in the folder:

included libraries.png

If you compare the code above with the contents of the settings folder you will see how this works. Now you can use any of the code in the library in your application.

Note: You might think that just adding the include directives above would make it possible for your program to use the included files. This is not so. The Arduino IDE does some behind the scenes shenanigans to link these includes to your library which will result in you getting errors when you build the program.