5

In MSVC & C#, #pragma region can be used to label a code section.
Similarly, in GCC/Clang, #pragma mark can accomplish the same thing.

Is it possible to define a single macro such as CODELABEL(label) which will work for both compilers?

Basically, I'd like to avoid having to do the following:

#ifdef _WIN32
#pragma region Variables
#else
#pragma mark Variables
#endif
bool MyBool;
int MyInt;

#ifdef _WIN32
#pragma region Methods
#else
#pragma mark Methods
#endif
void MyMethod();
void AnotherMethod();

... and instead, do something like this:

CODELABEL( Variables )
bool MyBool;
int MyInt;
CODELABEL( Functions )
void MyMethod();
void AnotherMethod();

Is something like this possible?

RectangleEquals
  • 1,825
  • 2
  • 25
  • 44

3 Answers3

6

Yes, in C++11, you can use _Pragma, since using #pragma in a macro definition is not allowed:

#ifdef _WIN32
#define PRAGMA(x) __pragma(x) //it seems like _Pragma isn't supported in MSVC
#else
#define PRAGMA(x) _Pragma(#x)
#endif

#ifdef _WIN32
#define CODELABEL(label) PRAGMA(region label)
#else
#define CODELABEL(label) PRAGMA(mark label)
#endif

The dance with PRAGMA is to satisfy _Pragma requiring a string literal, where side-by-side concatenation of two string literals (e.g., "mark" "section label") doesn't work.

chris
  • 60,560
  • 13
  • 143
  • 205
  • This seems like it should work, but MSVC is giving me `error C2059: syntax error : 'string'` wherever `CODELABEL(MyLabel)` is used – RectangleEquals Sep 08 '15 at 23:51
  • @RectangleEquals, Without looking too far into it, I'm thinking `_Pragma` is unsupported (even with /Za, unlike [alternative tokens](http://stackoverflow.com/a/24414420/962089)), but it's had its own `__pragma`, so that works. – chris Sep 09 '15 at 00:02
  • Yep, that change seems to have done the trick. Haven't tested in OSX yet, though. – RectangleEquals Sep 09 '15 at 00:09
  • @RectangleEquals, My initial tests were with Clang if you mean that. – chris Sep 09 '15 at 00:10
  • Yeah, Clang. If you've tested with it and it worked, then I'd say this case is closed. – RectangleEquals Sep 09 '15 at 00:12
1

According to this topic, the following should work.

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

#ifdef _WIN32
  #define LABEL region
#else
  #define LABEL mark
#endif

and then

#pragma STR(LABEL) Variables
bool MyBool;
int MyInt;
#pragma STR(LABEL) Functions
void MyMethod();
void AnotherMethod();
Community
  • 1
  • 1
Zereges
  • 5,139
  • 1
  • 25
  • 49
0

As far as Windows and macOS are concerned, since Xcode 12 and Visual Studio 2019, you can easily use this syntax that works ok on both platforms:

#pragma region mark -
#pragma region mark Whathever Your Label

Xcode silently ignores the 'region' token while VS takes the 'mark' token as part of the label, which is a minor cosmetic issue, IMHO.

Anders
  • 221
  • 1
  • 6