aVC
aVC

Reputation: 2344

including functions in seperate file in arduino

Noob qn.

I was using Arduino 1.6.5 and I had something like below that used to work.

main.ino

#include "oldFunctions.h"

#define BLAHBLAH
setup(){
  //....
}
loop(){
  //....
}


void newFunctionA(void){
//....
}

oldFunctions.h. This is a file I added over time, with new functions and stuff.

void test(void){
   newFunctionA();
}

This used to work in Arduino 1.6.5, but I upgraded to 1.6.8 and now I get the error saying newFunctionA was not declared in this scope

Can someone help?

Upvotes: 2

Views: 1941

Answers (1)

frarugi87
frarugi87

Reputation: 2880

It's ALWAYS a bad idea messing up with the files and then hoping that the compiler does some magic. What I suggest you is to use the files as they are meant to be used, so

  • Header files (*.h, *.hpp) shall contain class definitions (but not implementations), global variables defined as extern, function prototypes. They shall use the common ifndef... to prevent multiple inclusions
  • Source files (*.c, *.cpp, *.ino) shall contain the actual function implementations, the methods implementations, and the global variables definitions.

You should not avoid using this, otherwise you will enter a lot of possible troubles.

In your case, you should then have three files:

main.ino

#include "oldFunctions.h"

#define BLAHBLAH
setup(){
  //....
}
loop(){
  //....
}

void newFunctionA(void){
//....
}

oldFunctions.h

#ifndef OLD_FUNCTIONS_H
#define OLD_FUNCTIONS_H

void newFunctionA();
void test();

#endif

oldFunctions.cpp

#include "oldFunctions.h"

void test(void){
    newFunctionA();
}

Please note, however, that in the cpp file you should not use the BLAHBLAH you defined in main.ino. If you need it, move it to the oldfunctions.h file.

In newFunctionA is a new function you want to keep separated from the oldfunctions, just create a new header file and include it. The important part is that you do not rely on arduino joining the source files, because this can lead to unexpected behavior.

Upvotes: 5

Related Questions