1

I am trying to hide libraries behind another, for simplicity. But I can't deal with the objects required by the libraries. Basically I want to use the objects both in my .cpp and .ino file, but I am getting errors about double definition, or not declared in this scope.

test.ino

#include "lib.h"
#include "obj.cpp"

void setup() {
  mesh.setNodeID(40);
  mesh.begin();
}

void loop() {
  mesh.update();
}

lib.cpp

#include "Arduino.h"
#include "lib.h"

#include "obj.cpp"

int message = 1;

void send() {

  if (!mesh.write(&message, 'C', sizeof(message))) {

    // If a write fails, check connectivity to the mesh network
    if ( ! mesh.checkConnection() ) {
      //refresh the network address
      Serial.println("Renewing Address");
      mesh.renewAddress();
    } else {
      Serial.println("Sending failed, Test OK");
    }
  } else {
    Serial.print("Sent OK");
  }
}

lib.h

#ifndef lib_h
#define lib_h

void send();

#endif

obj.cpp

#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>
#include <EEPROM.h>

RF24 radio(7, 8);
RF24Network network(radio);
RF24Mesh mesh(radio, network);
1
#include "obj.cpp"

Don't include .cpp files. That gets them compiled twice (or more) and then you get duplicate definitions. Include .h files only.

What you are calling obj.cpp should probably be obj.h, however I haven't actually tried to compile it.


it says that I have multiple definitions of the three objects

I tried compiling but I don't have the RF24 library. Anyway, this is wrong:

obj.h

#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>
#include <EEPROM.h>

RF24 radio(7, 8);
RF24Network network(radio);
RF24Mesh mesh(radio, network);

You can't define things there (like radio) which get included in multiple files. obj.h or obj.cpp it will be the same thing.

These lines need to be in one .cpp file:

RF24 radio(7, 8);
RF24Network network(radio);
RF24Mesh mesh(radio, network);

Thus you cannot include that file in another file. However you can refer to them by making them extern in a header file, eg.

extern RF24 radio;
extern RF24Network network;
extern RF24Mesh mesh;
1
  • I changed obj.cpp to obj.h but it says that I have multiple definitions of the three objects: sketch\test.ino.cpp.o:(.bss.mesh+0x0): multiple definition of mesh' sketch\lib.cpp.o:(.bss.mesh+0x0): first defined here sketch\test.ino.cpp.o: In function setup': D:\\test/test.ino:4: multiple definition of radio' sketch\lib.cpp.o:(.bss.radio+0x0): first defined here sketch\test.ino.cpp.o: In function setup': D:\\test/test.ino:4: multiple definition of `network' sketch\lib.cpp.o:(.bss.network+0x0): first defined here collect2.exe: error: ld returned 1 exit status exit status 1 Feb 15 '16 at 4:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.