chipKIT® Development Platform

Inspired by Arduino™

simple example, linking error

Created Fri, 16 Oct 2015 16:44:54 +0000 by wildmage


wildmage

Fri, 16 Oct 2015 16:44:54 +0000

I am trying to understand what I'm doing wrong with this sketch code. I have 3 files in my sketch library. They are the following:

sketch_oct15a:

#include "test.h"

void setup() { otherFunc(); }

void loop() {

}


test.h:

void otherFunc();


test.c:

void otherFunc() {

}


When I compile these files within MPIDE, the object files are created but fails at the linking step. The error message on the console says:

sketch_oct15a.cpp.o: In function setup': /privatesketch_oct15a.cpp:16: undefined reference to otherFunc()' collect2: ld returned 1 exit status

Can someone tell me what I'm doing wrong? It seems that otherFunc() is properly declared and defined, but it is not linking properly.


majenko

Fri, 16 Oct 2015 16:55:09 +0000

The problem here is that of "link context". The way that C++ works is it "munges" the function names into a different form than C does. So for instance, when you include your header file, it munges the prototype in there into the C++ form because you're including it in a C++ file. And of course that munged version doesn't match the C version of the function and the linker can't find it.

So you need to tell the compiler that "this function is a C function not a C++ function" so it doesn't munge it, and you can do that with 'extern "C"'. But you only really want to do it if you're in a C++ file not a C file, so you need to wrap it all in a bit of precompiler magic as well.

So your header file should look like:

#ifdef __cplusplus
extern "C" {
#endif

void otherFunc();

#ifdef __cplusplus
}
#endif

Alternatively change you C file into a C++ file so it performs the same munging.

You can read more about it all here: https://isocpp.org/wiki/faq/mixing-c-and-cpp


wildmage

Fri, 16 Oct 2015 17:47:56 +0000

Thank you. That works. Didn't realize the main sketch file was c++.

Renaming test.c to test.cpp also works.