Search code examples
c++regionpragmapreprocessor-directive

Cross-platform code label macro?


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?


Solution

  • 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.