2

I'd like to know if it's possible to create a library for Arduino that does not contain a class, just functions.

I know how to create a library with a class, but I'd like to create a library of general purpose functions that don't need to be instantiated to be used. Just used like the standard functions included in the Arduino IDE: sizeof(), etc..

Is this possible? If so, can anyone point me in the direction of a template? I've been searching, but haven't found anything.

Thanks!

  • Have you tried creating a library like you've done before but not putting any classes in it? – Ignacio Vazquez-Abrams Jun 14 '16 at 20:13
  • 1
    Although this is not directly relevant to your question, sizeof(), like if() is NOT a function (although its syntax looks like one), it is an operator evaluated at compile time. – Alphonsos_Pangas Jun 14 '16 at 21:05
  • Ok, I was hoping this was possible, I read here that it wasn't possible: stackoverflow.com/questions/1735990/… A few points down the page, someone wrote: > On Arduino you can use classes, but there are a few restrictions: 1. No new and delete keywords 2. No exceptions 3. No libstdc++, hence no standard functions, templates or classes You also need to make new files for your classes, you can't just declare them in your main sketch. You also will need to close the Arduino IDE when recompiling a library. That is why I use Eclipse as my Arduino IDE. No standard – Killerb81 Jun 14 '16 at 21:08
  • No new and delete keywords 2. No exceptions 3. No libstdc++, hence no standard functions, templates or classes - most of that is nonsense. You can use new and delete these days. You can use templates and classes. You can get the STL (standard template library) from StandardCplusplus. You have standard functions like malloc, memcpy, strcpy, etc. – Nick Gammon Jun 14 '16 at 22:30
  • You also will need to close the Arduino IDE when recompiling a library - when I am developing a library I use a standalone editor for editing the library. I don't need to close the IDE to test it. – Nick Gammon Jun 14 '16 at 22:33
3

Yes, it's possible.

Just don't make a class. Just make functions instead.

Like a class-based one, have a .cpp and a .h file. In the .cpp file (or .c file if you don't want any of the C++ functionality or 90% of the Arduino API available to you) place your functions.

In the .h file place prototypes for them. I am in the habit of adding the extern keyword, but you don't actually need to for functions.

For example:

foo.cpp:

void doSomething() {
    // whatever
}

foo.h:

extern void doSomething();

Then you can include your .h file and call your functions:

#include <foo.h>

// ...

doSomething();
| improve this answer | |

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.