2

I'm writing an Arduino program that contains various .h and .cpp files. Due to organizational needs, I have configured the directory that contains my Arduino sketch (.ino) to possess a subdirectory. This subdirectory contains related source code.

An example layout of my project directory is located below:

mysketch
    mysketch.ino
    mycode.h
    mycode.cpp
    mylibs
        mylib1.h
        mylib1.cpp
        mylib2.h
        mylib2.cpp
        mylib3.h
        mylib3.cpp

With this, I'm able to successfully #include the header files. However, the compiler then complains that mylib1.cpp, mylib2.cpp, and mylib3.cpp are not defined (however they are). I'm guessing that the Arduino only looks for source files within the same directory that the sketch lives in. Thus subdirectories contains source code are ignored.

I can then modify my directory layout such that all of the 'mylib.h/.cpp's' are in the same directory and the project compiles fine.

So my question: how do I configure the Arduino IDE to reference source code within a subdirectory? Also, I would prefer that the mylibs exist within the same directory, and not within the Arduino 'library' directory. This will allow me to then easily distribute the code as a single zipped folder.

1

In the Arduino IDE the answer is simple: you can't.

The Arduino IDE doesn't compile within the directory your sketch is in. Instead it writes out a fresh copy of all the files directly from the tabs in the IDE into a temporary build folder (munging them as it goes if they are .INO or .PDE) and then compiles them there. Anything else within your sketch folder is completely ignored.

If you want that kind of functionality you will have to use a different IDE.

For example, UECIDE lets you have a structure like:

MySketch/
    MySketch.ino
    libraries/
        MyLib1/
            MyLib1.h
            MyLib1.cpp
        MyLib2/
            MyLib2.h
            MyLib2.cpp
1

The behavior of the Arduino IDE with this sort of thing has changed over time so it depends on which version of the Arduino IDE you're using. With recent versions you can put the files in a src subfolder of your sketch folder and then do:

#include "src/mylib1.h"

or:

#include "src/mylib1/mylib1.h"

depending on how you want to organize the folder structure.

When doing this you may find that Arduino libraries often use incorrect include syntax in their source code. For example in mylib1.cpp:

#include <mylib1.h>

although wrong, would still work if the library was located in one of the Arduino libraries folders but with the library located in the sketch folder this no longer works and you need to change it to:

#include "mylib1.h"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.