Question about class reuse

Hi, I’m new to PlatformIO with VSCode. I just switched over from Arduino IDE and everything seems to be working well so far. I’m very excited about having a “real” IDE to work in.

My question is this. I have a couple of classes that I have written for general purpose things, such as a timer class and a switch class with debounce logic. Currently I am physically copying the .cpp and .h files into each project that I use them in. However, this seems like a terrible way to do things, as any changes require recopying to each project. Is there a best practice for how I should go about organizing these classes and then including them into the necessary projects? Should each class be its own PlatformIO project? One project? Not even a project, just a folder somewhere with the class files in it? Some other fourth thing?

Sorry, this probably isn’t even a PlatformIO question but more of a general C++ question, but I am clueless as to how this should be properly laid out and configured.

Thank you,
mmitchellmoss

There are multiple options. First, you should read through the extensive library configuration and creation documentation.

One option would be to put each functional unit (e.g., all the files for the debounce logic and class or timers) in a newly created folder, serving as a library folder. For folder structure see docs. That folder can then be referenced by other PlatformIO projects by adding a lib_deps expression using the file:// protocol.

Meaning that e.g. if there’s a folder C:\mylibs\TimerLibrary with a .h and .cpp file inside, that library folder can be included in the project by writing

lib_deps = 
   file://C:\mylibs\TimerLibrary

(or extending the previous lib_deps expression).

An easier way would be to add the entire C:\mylibs folder as a library lookup folder that PlatformIO will search for inner library folders when you reference a library in code. Per docs above, that can be done by

lib_extra_dirs = C:\mylibs

(that is also one way that someone can keep all old Arduino-IDE installed libraries, by pointing to the Arduino-IDE lib folder).

That way you have the code files only once in a folder that all projects reference.

Thank you Max for the well written and informative response. I really appreciate it. I think this totally answered my question. Before I attempt to change anything I will read the documentation links that you sent me as well. Thank you again very much.

As an update, I did read the documentation. After seeing that you can set lib_deps equal to a http address for a github repository I decided to break my classes out into individual projects pushed to github. Then after adding the URLs to my lib_deps statement, everything worked great. Awesome and thanks again.