Multi-files arduino project

Hi everyone, I’m new here and I gonna ask a little doubt.

I have a project coded by Arduino IDE and is a… really big project, so when I programed it, I decided organize it by several files. So, it works (In that moment with Arduino IDE).

Right now I imported that project to PlatformIO, but unlike arduino, the files doesn’t works together. So, doesn’t works the declarations that are initializated in other file, or calls to functions in other file.

I would like know how I can do for work in PlatformIO with multi-files as I can do in arduino.

Thanks a lot

The Arduino IDE works by whacking all the files together and, doing some pre-processing to make the file actually work when fed to the compiler, and then compiling it. PlatformIO unfortunately doesn’t do that pre-processing, hence why you’re having trouble.

There are a couple of things you need to do

  • structure your code with function declarations and definitions - otherwise known as forward declaration. This can be done by simply copying that first line of your function (the line that specifies it’s name, any parameters it takes, and if it returns anything) and then, depending on whether it is the main file, or one of the extra files you either place it at the top of the main file, or as a header file that accompanies one of the extra files.
  • ensuring your main code knows about those header files - #include them. You should also add include guards to those files to prevent hard to spot recursive include errors in the future.
  • ensure external variables are declared appropriately. i.e. if one of your sub-files uses a variable to share something with the main code unit, it actually needs to be defined in the main file as an external variable so the compiler knows about variable when it processes that main file, and that it is coming from another file.

There might be a few other things that need to be tweaked and bashed, but that’s the gist of it. Basically, have a read of Chapter 2 of www.learncpp.com and become familiar with the concepts it outlines. Changing the code to be standard C++ rather than Arduinoese won’t hurt either if you go need to go back to the Arduino IDE, as it simply won’t need to do as much behind the scenes changing of your code to make it compile.

Ok, in addition, yerterday I was looking for some informatin about multi-files in C++, and I see 2 ideas:

As you said, create de function in an auxiliary file, and put a “declaration” of it at main.
Make an #include “file_name.ino”, or “file_name.cpp”

I probe the second idea and works… fine, although with big programs could have problems

1 Like