Artium
Artium

Reputation: 5329

Arduino Linker Errors When Using a Spesific Namespace Name

I am trying to write an Arduino library.

I have put all my code inside a namespace and got some linker errors.

Strangely, when I changed the name of the namespace these errors were gone.

My question is what could be the cause of this? Can it be that this namespace is already used by some other library?

Minimal example:

at24c256.h

#ifndef AT24C256
#define AT24C256

namespace AT24C256 {
  int f();
}

#endif

at24c256.cpp

#include "at24c256.h"

namespace AT24C256 {
  int f() {return 42;}
}

And then in the sketch, I just call AT24C256::f().

#include "at24c256.h"

void setup() { 
}

void loop() {
    AT24C256::f();
}

All three files are in the same directory. The error I got in this case is:

sketch_dec13b.cpp: In function ‘void loop()’:
sketch_dec13b.cpp:155:13: error: ‘::f’ has not been declared

If I change AT24C256 to something else, the build completes without errors.

Update:

I accidentally posted the wrong error message. What I actually get is this:

sketch_jan04a.cpp.o: In function `loop':
sketch_jan04a.cpp:10: undefined reference to `(anonymous namespace)::f()'
collect2: ld returned 1 exit status

Upvotes: 1

Views: 1030

Answers (2)

harper
harper

Reputation: 13690

‘::f’ has not been declared

This shows us that you call the function f() at global scope. When you want to use the function you must be in the same scope or specify the scope explicitly.

Edit

Your header file shows the problem now after your edit:

#ifndef AT24C256
#define AT24C256

namespace AT24C256 {

Your are using an anonymous namespace.

AT24C256::f() leaves the preprocessor as ::f()

Upvotes: 1

Artium
Artium

Reputation: 5329

Oh, I finally found out what the problem was. The include guards defined AT24C256 which is exactly the name of my namespace, so it was preprocessed into nothing.

Upvotes: 1

Related Questions