I have a header and implementation file defined as follows.
test.cpp
namespace test
{
class Ctest
{
public:
Ctest() {};
void a() {};
};
};
test.h #ifndef rocketbot_remote_control_h #define rocketbot_remote_control_h
namespace test
{
class Ctest
{
public:
// Ctest();
void a();
};
}; #endif
main
#include "test.h"
using namespace test;
test::Ctest r;
//Ctest r;
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
r.a();
}
I get the following linker error. Could anyone shed light on how can I instantiate and use the object/methods on that object.
Arduino: 1.6.5 (Windows 8.1), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"
sketch_jan07a.cpp.o: In function loop': C:\Program Files (x86)\Arduino/sketch_jan07a.ino:14: undefined reference to test::Ctest::a()'
collect2.exe: error: ld returned 1 exit status
Error compiling.
The problem is that you have defined the class twice, once in the H file and again in the CPP file. You should only have the class definition in the H file, and simply include the H file in the CPP. The definitions are different (one has a default constructor and an empty implementation of a(), the other has neither), so I think that's why the mistake manifests as a linker error... it may be resolving the r.a() reference to the version of Ctest without an implementation of a().
Instead:
#ifndef rocketbot_remote_control_h
#define rocketbot_remote_control_h
namespace test
{
class Ctest
{
public:
void a(); // implementation of `a` is elsewhere (in the CPP)
};
};
#endif
#include "test.h"
namespace test
{
void Ctest::a() // Implementation promised by H file
{
// empty for now...
}
};
#include "test.h"
test::Ctest r;
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
r.a();
}
And please use [code]...[/code] tags around the snippets.