SPI driver

A newbie question :confused:
There can be several SPI libraries in the Arduino folder structure using the same names (SPI.h & SPI.cpp).
How does the compiler know which one to use if I add #include <SPI.h> to my source code?

When multiple libraries are found that match an #include directive, there are a few factors the Arduino IDE uses to determine which library to use:

  • Architecture match between the board (as determined by the architecture folder name of its hardware package) and the library (as determined by the architectures field in library.properties). Explicit match > wildcard match > mismatch. If a library has no library.properties or no architectures field in library.properties, that is considered a wildcard architecture match.
  • Filename/folder name match. If the library folder name matches the filename in the #include directive, that library is given preference.
  • Library location. {sketchbook folder}/libraries > {hardware package folder}/libraries > {Arduino IDE installation folder}/libraries

The other thing you should know is that only the libraries bundled with the hardware package of the board you're compiling for are accessible. Libraries bundled with other hardware packages are ignored so they don't even come into the equation. Typically, you would only find the SPI library bundled with the hardware package, since it's architecture specific. The exception would be if you had installed a version of the SPI library to {sketchbook folder}/libraries in order to customize it. In that case, the architecture matching factor will cause the custom SPI library to be used when you have a board selected that matches the architecture (because the sketchbook folder gets preference), but if you have a board selected that does not match the architecture then the SPI library bundled with its hardware package will be used instead.

This system usually does a good job of picking the correct library but in some cases it does end up grabbing a different library than you had intended. To make this less of an issue, the Arduino IDE will display a list of the matching libraries it found and which it used in the black console window at the bottom of the Arduino IDE window. When it thinks the information is not critical, it may only show it if you have File > Preferences > Show verbose output during compilation enabled. So if you're in doubt, it's a good idea to turn that option on at least for one compilation.

Hi Pert, Thank you very much for the detailed explanation. This should help in resolving an issue I'm having with multiple header files with the same name. Regards, Robert

You're welcome. I'm glad if I was able to be of assistance. Enjoy! Per