Go Down

Topic: how to use additional .c files in a sketch (Read 484 times) previous topic - next topic

beginner

I am a beginner with the Arduino environment and I need some help figuring out how to use some .c source files in a sketch without creating a library. I tried to find the answer on the forum but I couldn't, I apologize if the solution to my problem is somewhere in the posts and I just missed it.

So, I have a test.h file that contains only:

Code: [Select]

void doSomething(void);


The test.c file contains:

Code: [Select]

#include "test.h"

void doSomething(void)
{
     // there should be some code here
}


In my sketch, I have:

Code: [Select]

#include "test.h"

void setup()
{
 doSomething();
}

void loop()
{
}


I am not sure if this was needed or not but I also went to the Sketch menu and use Add File... to include both .h and .c file.

When I compile I get:

Code: [Select]

o: In function `setup':
C:\DOCUME~1\coprea\LOCALS~1\Temp\build50525.tmp/Temporary_3386_6704.cpp:6: undefined reference to `doSomething()'


C:\DOCUME~1\coprea\LOCALS~1\Temp\build50525.tmp/Temporary_3386_6704.cpp:8: undefined reference to `doSomething()'



If I understand correctly from the Build Process page, this should work so I am sure I am missing something. Thanks for your help in advance!

mikalhart

#1
Dec 10, 2008, 05:47 am Last Edit: Dec 10, 2008, 05:48 am by mikalhart Reason: 1
beginner--

The problem stems from the fact that you are trying to link a C function from a C++ module, without explicitly declaring that fact.  There are several solutions, including:

a) rename test.c to test.cpp
b) remove the #include "test.h" from your main sketch and replace it with
Code: [Select]
extern "C" void doSomething(void);
c) change the header to the clumsy:

Code: [Select]
#if defined(__cplusplus)
extern "C"
{
#endif
void doSomething(void);
#if defined(__cplusplus)
}
#endif


etc.

Mikal


beginner

#2
Dec 10, 2008, 02:41 pm Last Edit: Dec 10, 2008, 02:42 pm by merlin13 Reason: 1
Thank you very very much for taking the time to explain this to me, I used the first alternative and it works great.

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy