4
votes

This should be a simple problem. I'm trying to split up code into two files within a sketch:

test.ino:

void setup(){}
void loop(){ fn(); }

test.c:

char myChar = '?';
void fn(){ myChar++; }

I've tried using a test.h file with various configurations such as having the lines:

  • extern char myChar;,
  • char myChar;
  • void fn();
  • extern void fn();

And various combinations of including test.c and test.h files in the different files, but I always get one compiler error or another, such as:

test.cpp.o:(.data.myChar+0x0): multiple definition of `myChar'

test.c.o:(.data.myChar+0x0): first defined here

Or

test.cpp.o: In function `setup':

C:\Program Files\arduino-1.0.4/test.ino:4: undefined reference to `fn()'

I'm really pulling my hair out with this one. Any help would be greatly appreciated

2
I'm not familiar with the .ino extension? Is this a c++ file? In that case you might need to use C linkage if your function is defined in a C file. You can do that like this: extern "C" void fn()hojusaram

2 Answers

4
votes

The Arduino IDE is really meant for beginning programmers. As you become better, you may want to branch off into more traditional programming tools.

Arduino projects are really just c/c++ applications. In that respect, you have the entire c/c++ community at your back. One of their most loved and despised tools is called make. You can deploy and build your project with it. Here is a great starting point. http://ed.am/dev/make/arduino-mk/arduino.mk

1
votes

You should first try to understand the difference between declaration and definition of a variable. Fortunately this was already discussed at stackoverflow here and here.

The point is to put all declarations into a header file (.h) and all the definitions into an implementation file (.c). The final step is then to ensure that the header will only get included once. This is achieved with so called include guards. The details are again already known on stackoverflow here and here.