0

When implementing a function in CPP, I am used to put my helper functions in an anonymous namespace, so they don't pollute the global namespace outside the CPP file where they are defined.

However, the same doesn't seem to apply to using declarations? I.e., it seems that I can put them outside the anomymous namespace, and they still don't leak to the global namespace. What is special about them?

In the following example, I feel I should I put using std::cout in the anonymous namespace to avoid polluting the global namespace. But things are also fine as they are: attempting to use cout in main.cpp errors.

myHeader.hpp

#pragma once

namespace myNamespace {
void print (int);
}

mySource.cpp

#include <iostream>
#include "myHeader.hpp"

namespace {
  // I need to put helperFunction here so it is only visible in this file.
  void helperFunction () { /*Do stuff ...*/ }
}

// This declaration only applies to this file as if it were in the anonymous namespace. How?
using std::cout;

void myNamespace::print (int value) {
  helperFunction();
  cout << value << std::endl;
} 

myMain.cpp

#include <iostream>
#include "myHeader.hpp"

int main () {
  myNamespace::print(42);

  // helperFunction(); // This would error.
  // cout << 42; // I want this to error too.
  return 0;
}
Antonio
  • 355
  • 1
  • 2
  • 13
  • 2
    If you don't `#include` the .cpp file, the `using` declaration won't leak either way. – paolo Jul 18 '22 at 09:32
  • 2
    `// I want this to error too.` This is an error, no? Did you actually try? – 463035818_is_not_an_ai Jul 18 '22 at 09:34
  • Thanks - I might have to clarify the question: I know that `cout` in the main errors, but I would like to know what is special about `using` declarations that makes them not leak in the global namespace even if they are not in the anonymous namespace. – Antonio Jul 18 '22 at 09:36
  • Aside: consider `#pragma once` as an optimisation, in terms of compilation times. It's fallible, you should also use a good old-fashioned [header guard](https://stackoverflow.com/questions/4767068/header-guards-in-c-and-c). – Paul Sanders Jul 18 '22 at 09:37
  • 1
    nothing special. Separate translation units are compiled separately. `main.cpp` knows nothing about `mySource.cpp` – 463035818_is_not_an_ai Jul 18 '22 at 09:41
  • 1
    related: https://stackoverflow.com/q/9164476/4117728 – 463035818_is_not_an_ai Jul 18 '22 at 09:51

0 Answers0