Hi - I am trying to figure out how to call functions that have been defined in code brought in through #include. I imagine this has come up a lot, so sorry- I did some searches on the forum but couldn't find anything relevant.
For learning purposes I've just created a test sketch, test.c and test.h files. How do I call the function in test.c ('doTest()'). And for that matter, how are variables within included files made available within a sketch?
Finally (!) Is it better/different to use a tab for each .c + .h file? Is that the piece I am looking for? My simple test code is below.
Thanks for any tips - this is a real stumper for me.
---Roy
#include <test.h>
void setup(){
//do some set up
}
void loop(){
doTest();
}
--test.h
#ifndef _TEST_H
#define _TEST_H
#include <inttypes.h>
//define some stuff
#endif
The C compiler saw you try to use your doTest() function but at that point in the compilation it had no idea what kind of value (if any) the function was supposed to return - hence the error.
The tool for avoiding the problem is called a prototype which tells the C compiler what to expect from doTest. A prototype is simply the function declaration followed by a semicolon.
You need to put a prototype for your doTest() function in your test.h header file. Simply add the same line that you use when you declare the function in your test.c file followed by a semicolon - like this:
test.h
#ifndef _TEST_H
#define _TEST_H
#include <inttypes.h>
void doTest(); // this is the prototype - when the compiler sees this it
// makes a note to itself to expect to find a function named
// doTest further on in the code and that doTest() returns
// no value and has no parameters. (if it did have parameters
// you would include them in the prototype also).
//define some stuff
#endif
When the compiler reads your main sketch file and runs into the #include "test.h" line it immediately reads in the header file. It will see the prototype for doTest() and from that point on it will know all it needs to know to handle it when it runs into it later.
I believe the import library command assumes the header and code files as well as the folder that they are in have the same root name and that the code file is .cpp
Glad you got it compiling.
I don't think you need to specifically #include test.c in your main sketch file though so long as it's present in a tab in the IDE which sketch/add file does for you.