Arduino & C: put a function and global variable in external file

12,407

Solution 1

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

Solution 2

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.

Share:
12,407
CL22
Author by

CL22

Updated on June 04, 2022

Comments

  • CL22
    CL22 almost 2 years

    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