I'm trying to get a rather large sketch working with a teensy LC. I'd like to break it into headers and C files, but the multi-file sketch fails to compile. When I put everything into a single, monolithic sketch, it runs fine. I've #included the h files where they are needed, using single quotes, and have confirmed that my h files are in the same folder as my sketch. Is there an additional step to go through specific to teensy? I've managed to do this tons of times using a standard arduino.
Here is a basic sketch:
This is the main sketch file:
#include "tst.h"
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
doNothing();
}
This is tst.h
void doNothing();
This is tst.c
#include "tst.h"
void doNothing()
{
int i = 0;
}
I get the error "undefined reference to doNothing() in function loop"
1 Answer 1
I get the error "undefined reference to doNothing() in function loop"
The C++ compiler cannot find doNothing(). This is mainly due to the incomplete header file and mix of C and C++.
Two things are needed to avoid this type of problem; 1) protect the file from multiple includes (in the same compile), 2) make the function visible to the C++ compiler as a C function (without name mangling).
tst.h:
#ifndef TST_H
#define TST_H
#ifdef __cplusplus
extern "C"{
#endif
void doNothing();
#ifdef __cplusplus
} // extern "C"
#endif
#endif
Cheers!
-
I admit I'm still learning c++, but why is my function not c++?Michael Stachowsky– Michael Stachowsky2016年12月26日 14:14:28 +00:00Commented Dec 26, 2016 at 14:14
-
The build rules for files with the extension .c will use the c-compiler (gcc). If you rename the file and use the extension .cpp the build rules will use the c++-compiler.Mikael Patel– Mikael Patel2016年12月26日 14:35:01 +00:00Commented Dec 26, 2016 at 14:35
-
Oh, yes I see. So the function itself was not strictly c, but the fact that it was in A C file was the problem?Michael Stachowsky– Michael Stachowsky2016年12月26日 14:49:17 +00:00Commented Dec 26, 2016 at 14:49
-
Correct! If you had used overloading, reference parameters, classes, etc (i.e. a language difference) then the C-compiler would have flagged an error. Now actually the linker flags the error as the C function does not have the same compiled name (aka manged name) as the C++ function.Mikael Patel– Mikael Patel2016年12月26日 14:54:24 +00:00Commented Dec 26, 2016 at 14:54
".c"
file instead of".cpp"
?"test.c"
and the"test.h"
appear on the top, the"test.c"
seems to be compiled"mylib.c.o"
and thedoNothing
is present inside. But the error is alwaysUsingCpp.ino:14: undefined reference to 'doNothing()'
.