Go Down

Topic: Function defined in header not available in main file (Read 453 times) previous topic - next topic

ashrj

I have a file structure as follows:
Code: [Select]

interface.h --> interface.c
      |
      |
effects.h --> effects.c
      |
      |
    main


However, functions declared in effects.h are not accessible in main.

Code snippets :

main :

Code: [Select]
#include "interface.h"
#include "effects.h"
void setup()  //Initialize all variables here
{

....
turnoff();
};


effects.h :

Code: [Select]
#ifndef EFFECTS
#define EFFECTS
void turnoff();
#endif


effects.c :

Code: [Select]
#include "interface.h"
#include "effects.h"
void turnoff()
{
....
};


interface.h :

Code: [Select]
#ifndef INTERFACE
#define INTERFACE
....
#endif


Error message : In function ``loop':undefined reference to ``turnoff()'

Anybody knows whats wrong ?

PaulS

Quote
Anybody knows whats wrong ?

I c what the problem is. Changing to cpp would help.

ashrj

#2
Feb 10, 2013, 04:24 pm Last Edit: Feb 10, 2013, 04:28 pm by ashrj Reason: 1
Why ? Doesnt avr-gcc handle c ??

http://arduino.cc/en/Hacking/BuildProcess

PaulS

Yes, it does. However, C++ supports function overloading. That is the same function can be called with different arguments. How do you suppose the compiler knows which code to actually execute when you type Serial.print(val);?

The answer is that every function really gets a different name. That name is made up of the function name and the types of the arguments that the function accepts.

So, Serial.print() for an int is a different name what Serial.print() for a float.

The C++ compiler is looking for a function based on the name and the arguments that the function accepts.

The C compiler, because it does not support function overloading, knows that the function name is unique, so it doesn't mangle the name.

The linker, then, can't find the mangled name it is looking for in the object file produced by the C compiler.

ashrj

I changed the files to .cpp and it worked. What I still dont understand is why ? If my project is completely in C or C++ then the linker should be able to handle it. What you describe should cause problems when i mix C and C++ together, if I understood you correctly.

PaulS

Quote
What I still dont understand is why ?

I described why. You could google "C++ name mangling" for more details.

Quote
If my project is completely in C or C++ then the linker should be able to handle it.

And it can. The IDE creates a cpp file from the sketch, though.

Quote
What you describe should cause problems when i mix C and C++ together, if I understood you correctly.

Well? Didn't it?

Go Up