Namespaces in Library Header Files?

I cannot get namespaces to work at all when they are declared inside of a library header file. I am creating my own library, and have headers that declare classes inside of custom namespaces. When I try to instantiate one of these classes in a sketch, the Arduino compiler does not recognize the custom namespace and throws a bunch of errors. I wrote a very simple test program to demonstrate my problem:

Library Header File (testlibrary.h):


namespace testnamespace
   struct teststruct
       int testvar;


Here is the sketch:

#include <testlibrary.h>

void setup()
   testnamespace::teststruct testinstance;

This gives the following compiler error:

error: 'testnamespace' has not been declared
error: expected constructor, destructor, or type conversion before 'testinstance'

I know that the library has been imported properly, because the code works just fine if I remove the namespace usage from the header and the sketch. If I move the header file code directly into the sketch, then it all works just fine, namespaces and all. For some reason it has something to do with the namespaces being used in either a library, header file, or both.

What am I doing wrong here?

I have solved my own issue, it had something to do with how the library was being imported.

When you add a library to Arduino through the IDE, it copies the library files into the arduino/libraries folder. You can modify contents of the files in this directory WITHOUT having to re-add the library through the IDE. However, if you modify the files themselves (e.g. add a file, delete a file, rename a file, etc), then you DO have to re-add the library through the Arduino IDE.

It seems that, when you add a library, the IDE/sketch/compiler keeps a list of the library files in addition to copying the library files into the arduino/library folder. If you modify the file contents, thats fine, because the IDE still has a list of the library files it needs to refer to when compiling. However, if you add/delete/rename files in the arduino/libraries folder, the IDE's list of files is no longer valid. This forces you to re-add the library through the IDE so that the file list can be updated. I don't know why this supposed list is necessary, couldn't the IDE/sketch/compiler just grab all files in that folder with .h, .c, and .cpp extensions?

When you manually add a library to the user contributed library folder you have to stop and restart the IDE in order to make it available, so it is perhaps not a surprise that if you add a file to an existing library folder with the IDE open it is not recognised.

I have a similar problem ( ).

You can try “#include <testlibrary.h>”, and put all the libraries in the sketch ( ino ) folder.

It’s a shit, but it helps to develop.

Good luck!.