5

I am creating a simple library to test how multiple files in an Arduino program works. I have three files. MotorController.ino:

#include <motor.h>

void setup() {
   motorInitialize();
}

void loop() {

}

motor.cpp:

#include "motor.h"

void motorInitialize() {

  for (int i = 0; i < 4; i++) {
     motorArray[i].writeMicroseconds(2000);
     delay(1500);
     motorArray[i].writeMicroseconds(2000);
     delay(1500);
  }
  delay(1000);

}

and motor.h:

#ifndef _motor_h_
#define _motor_h_

#include "Arduino.h"
#include <Servo.h>

Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

void motorInitialize();
#endif

When I try to compile the program, I get the error:

libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor1'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor2'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor3'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor4'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motorArray'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

I have read similar posts on this issue, but none of the solutions seem to work for me. I've followed the instructions on the Arduino website on how to create a library, and that doesn't seem to resolve this issue.

Kyle Marino
  • 53
  • 1
  • 1
  • 3

1 Answers1

6

Although the motor (global) variables are defined in a header files, they are included in both cpp files, thus defined twice.

Make them extern, and than define them in the motor.cpp file.

In motor.h, change

Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

to

extern Servo motor1, motor2, motor3, motor4;
extern Servo motorArray[4];

In motor.cpp, add:

Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

As a side note, use consts for values 4 and 2000.

Michel Keijzers
  • 13,014
  • 7
  • 41
  • 58