0

I'd like to print for a debug reasons the namespace of the variable/function it is defined in. I'm trying to use the define directive:

#include <iostream>

#define NS Static
#define MAKESTRING(x) #x

namespace NS {
  int global_x = 8;
  void print_global_x() {

    //print global_x here:
    //std::cout << NS << ": " << global_x << std::endl;
    std::cout << MAKESTRING(NS) << "::global_x: " << global_x << std::endl;
  }
}

but at the #1 line I'm getting a namespace name is not allowed error while with the second approach (line #2) I'm getting just NS::global_x: 8 instead of Static::global_x: 8

How can I correct the code to get the desired result?

Daros7
  • 63
  • 5
  • What is `#define NS Static` for? – Vlad Feinstein Aug 19 '21 at 20:29
  • "I'm getting just `NS::global_x: 8`" Is that not correct? Why do you desire `global_x::global_x: 8`? – Drew Dormann Aug 19 '21 at 20:39
  • @DrewDormann Sorry I've corrected my answer. The expected result should be `Static::global_x: 8`. – Daros7 Aug 19 '21 at 20:43
  • 3
    `#define MAKESTRING_HELPER(x) #x` and then `#define MAKESTRING(x) MAKESTRING_HELPER(x)` – Eljay Aug 19 '21 at 20:48
  • @VladFeinstein It's just a simple _define_ instruction. I'm defining the `NS` as a shortcut of the `Static` string to use further in the code wherever I'd like to use the `Static` namespace. – Daros7 Aug 19 '21 at 20:48
  • @Eljay. Thx friend. That's what I was looking for! Can You please explain me HOW does it work (I'm a beginner in the topic...)? – Daros7 Aug 20 '21 at 13:34
  • The two-step macro is needed because of the order of expansion for token replacement. You want NS to become Static, but the NS *argument* to the macro is not expanded (hence the undesired behavior in your bug). Passing it to the helper macro allows it to be token substituted, which does what is wanted. If a non-macro was passed in, there is no token substitution, so passing to the helper is a benign no-op. – Eljay Aug 20 '21 at 15:41

0 Answers0