Using a namespace

Hey! I want to outsource some functions into their own file. But I do not want to write "MyClass::MyFunction()" all the time so I tried using a namespace. Something like this:

NamespaceTest.ino

#include "Utils.h"

using namespace utils;

void setup()
{
  Serial.begin(115200);
}

void loop()
{
  prnt("Hello World");
  delay(1000);
}

Utils.h

#ifndef UTILITIES
#define UTILITIES

#include "Arduino.h"

namespace utils
{

struct Utilities
{
  static void prnt(String msg)
  {
    Serial.println(msg);
  }
};

}  /* utils namespace */

#endif /* UTILITIES */

Writing "Utilities::prnt("Hello World")" works just fine. But without "Utilities::" I still get the error that "prnt()" is not in this scope. Maybe someone is able to tell me what my mistake is. Thanks!

You need to specify the "Utilities::" scope. If you don't, how is the compiler supposed to know you want the 'prnt()' function form inside the Utilities struct?

This works:

main.ino:

#include "Utils.h"

using namespace utils;

void setup() {
  Serial.begin(115200);
}

void loop() {
  prnt("Hello World");
  delay(1000);
}

Utils.h:

#ifndef UTILITIES
#define UTILITIES

#include "Arduino.h"

namespace utils {
void prnt(String msg);
}

#endif /* UTILITIES */

Utils.cpp:

#include "Utils.h"

using namespace utils;

namespace utils {
void prnt(String msg) {
  Serial.println(msg);
}
}

Ah, so I do need to split this into a header and an implementation. Thank you! :slight_smile:

And, if you hide the function inside a struct or a class, you still need to use the double-colon scope resolution operator.