Why does an `.ino` file have to be in a folder of the same name?

AFAIK, that is a quirk built into the Arduino IDE. The best workaround I can think of is a file structure something like:

ArduinoWorkspace --- /myproj/ ----+ /src/ --------+ myproj.cpp
                                  + myproj.ino    + sensor.h
                                                  + sensor.cpp
                                                  + (more files)

, where myproj.cpp just #include's main.cpp. This should leave your project files "clean" such that they should work in a more typical environment as well.

Update:

I borrowed the name "main" from your question, but on reflection, "main" is a reserved name, specifically, every C or C++ program has a main.c or main.cpp as its top level code, provided by the system if you don't provide one. So I avoided using that as the folder- and project-name (but feel free to try it) and I've updated the diagram. What you do need is a project folder and a .ino file within it, of the same name. The .ino file could

#include <src/anything-else-you-like>

, e.g., your top level code file, thus pulling everything else. You may need for your .ino to #include each of the files in the src folder, if it the compiler doesn't figure out on its own, that that's where your other files are.

BTW, if you do use the name main.cpp for your top file, it will have to call the setup() and loop() functions (and serial event function, if you use that). It's probably best to leave the name 'main' alone, let the system provide the same main every Arduino program gets by default, and write your project code the typical Arduino way -- starting with setup() and loop().


When you have a project made up of a number of .INO files, how is the IDE supposed to know which is the "main" one? During compilation the IDE concatenates all the .INO files together into one monolithic file. It does this starting with the "main" one and then appends each of the others alphabetically to the end.

It is done this way so that your includes and global variables, which you should put in your "main" .INO file, are at the start of the finished program.

In order to do this the IDE has to know which of the files is the "main" one. And the way it works that out is by finding the one which is named the same as the folder the sketch is in.

In UECIDE I take it a step further and turn the whole folder into a compound document so you no longer have to enter a folder and open a .INO file to open a sketch - the actual folder itself is the whole sketch project. Again this kind of folder is identified as having a .INO file within it that is named the same as the folder.

Tags:

Arduino Ide