I'm in a situation where I have code that looks like this :
#ifdef NOISE
#ifdef NOISE_2D
DECLARE_NOISE2D();
#else // NOISE_3D
DECLARE_NOISE3D();
#endif
#else
DECLARE_NO_NOISE();
#endif
Is there a way to have Clang-format look at this piece of code and format it as such :
#ifdef NOISE
#ifdef NOISE_2D
DECLARE_NOISE2D();
#else // NOISE_3D
DECLARE_NOISE3D();
#endif
#else
DECLARE_NO_NOISE();
#endif
The best I've been able to do is with IndentPPDirectives: BeforeHash, which gives this as a result :
#ifdef NOISE
#ifdef NOISE_2D
DECLARE_NOISE2D();
#else // NOISE_3D
DECLARE_NOISE3D();
#endif
#else
DECLARE_NO_NOISE();
#endif
I also tried to pass preprocessor directives as macro block starts and ends, but it seems like they don't get picked up (worth a try).
It looks like preprocessor directives and C++ code have their own indentation tree that they don't seem to share. Is there anyway to have Clang-format give the desired output, or alternatively, is there any other automatic formatter that would be able to provide this functionality ?
Related
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?
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.
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();
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.
I can do this in Visual C++ 2008 with Release (NDEBUG) setting:
debug.h
#ifdef _DEBUG
void debug_printf(const char* format, ...);
#else
#define debug_printf(format, v) __noop
#endif
debug.cpp
#include "stdafx.h" //#include "debug.h" is inside it
void debug_printf(const char* format, ...) {
//so much work here
}
but not anymore in Visual C++ 2013, I will get compile error in debug.cpp file. It seems I have to change the defining strategy in debug.h. But I wonder is there compiler setting to reenable again the old way?
Use a macro in the first case too, and let it call the actual function (which is named something different from the macro).
And in the second case, just have an empty macro body.
Use variadic macros.
Something like
#ifdef _DEBUG
# define debug_printf(fmt, ...) real_debug_printf(fmt, __VA_ARGS__)
#else
# define debug_printf(fmt, ...)
#endif
When _DEBUG is not defined, then the macro debug_printf is replaced by nothing (or rather, an empty line).
For example if I had this code:
#ifdef _DEBUG
mPluginsCfg = "plugins_d.cfg";
#else
mPluginsCfg = "plugins.cfg";
#endif
Can I define a macro that looks like
#define DEBUG_RELEASE(debug_code, release_code)
and then use it like this;
DEBUG_RELEASE(mPluginsCfg = "plugins_d.cfg";,mPluginsCfg = "plugins.cfg";)
I'm sure that it works, and I'm almost sure that it is defined to work.
#ifdef _DEBUG
#define DEBUG_RELEASE(d,r) d
#else
#define DEBUG_RELEASE(d,r) r
#endif
I'm unsure whether I've seen anything uglier in the wonderful world of preprocessor macros.
How should I write the below piece of code using macro function?
#ifdef LOG_ENABLED
m_logger->Log(szType,szMessage);
#endif
I have done something like mentioned below and it resulted in error:-
#define _LOG_MSG_CND_BEGIN_ #ifdef LOG_ENABLED
#define _LOG_MSG_CND_END_ #endif
#define WriteLogMessage(szType,szMessage) \
{\
_LOG_MSG_CND_BEGIN_\
m_logger->Log(szType,szMessage);\
_LOG_MSG_CND_END_\
}
Please let me know how to write macro function for the above three piece of code without any errors.
I have used inline function for the same piece of code but while debugging i saw that the inline function was not getting treated as inline function and so i want to use macro function in this case.
Inline function which i used was as mentioned below:-
inline void WriteLogMessage(LOG_LEVEL szType, LPCTSTR szMessage){
#ifdef LOG_ENABLED
m_logger->Log(szType,szMessage);
#endif
}
The standard C preprocessor is a bit of an idiot and doesn't understand much at all. You want something like this:
#if defined LOG_ENABLED
#define WriteLogMessage(szType,szMessage) m_logger->Log(szType,szMessage)
#else
#define WriteLogMessage(szType,szMessage)
#endif
Preprocessor directives need to be the first thing in a line:
#define _LOG_MSG_CND_BEGIN_
#ifdef LOG_ENABLED
#define _LOG_MSG_CND_END_
#endif
#define WriteLogMessage(szType,szMessage) \
{\
_LOG_MSG_CND_BEGIN_\
m_logger->Log(szType,szMessage);\
_LOG_MSG_CND_END_\
}
EDIT: If you want macros to be expanded to other macros, that's not possible.
I have encountered the #define pre-processor directive before while learning C, and then also encountered it in some code I read. But apart from using it to definite substitutions for constants and to define macros, I've not really understook the special case where it is used without a "body" or token-string.
Take for example this line:
#define OCSTR(X)
Just like that! What could be the use of this or better, when is this use of #define necessary?
This is used in two cases. The first and most frequent involves
conditional compilation:
#ifndef XYZ
#define XYZ
// ...
#endif
You've surely used this yourself for include guards, but it can also be
used for things like system dependencies:
#ifdef WIN32
// Windows specific code here...
#endif
(In this case, WIN32 is more likely defined on the command line, but it
could also be defined in a "config.hpp" file.) This would normally
only involve object-like macros (without an argument list or
parentheses).
The second would be a result of conditional compilation. Something
like:
#ifdef DEBUG
#define TEST(X) text(X)
#else
#define TEST(X)
#endif
That allows writing things like:
TEST(X);
which will call the function if DEBUG is defined, and do nothing if it
isn't.
Such macro usually appears in pair and inside conditional #ifdef as:
#ifdef _DEBUG
#define OCSTR(X)
#else
#define OCSTR(X) SOME_TOKENS_HERE
#endif
Another example,
#ifdef __cplusplus
#define NAMESPACE_BEGIN(X) namespace X {
#define NAMESPACE_END }
#else
#define NAMESPACE_BEGIN(X)
#define NAMESPACE_END
#endif
One odd case that I recently dug up to answer a question turned out to be simply commentary in nature. The code in question looked like:
void CLASS functionName(){
//
//
//
}
I discovered it was just an empty #define, which the author had chosen to document that the function accessed global variables in the project:
C++ syntax: void CLASS functionName()?
So not really that different from if it said /* CLASS */, except not allowing typos like /* CLAAS */...some other small benefits perhaps (?)
I agree with every answer, but I'd like to point out a small trivial thing.
Being a C purist I've grown up with the assertion that EACH AND EVERY #define should be an expression, so, even if it's common practice using:
#define WHATEVER
and test it with
#ifdef WHATEVER
I think it's always better writing:
#define WHATEVER (1)
also #debug macros shall be expressions:
#define DEBUG (xxx) (whatever you want for debugging, value)
In this way, you are completely safe from misuse of #macros and prevents nasty problems (especially in a 10 million line C project)
This can be used when you may want to silent some function. For example in debug mode you want to print some debug statements and in production code you want to omit them:
#ifdef DEBUG
#define PRINT(X) printf("%s", X)
#else
#define PRINT(X) // <----- silently removed
#endif
Usage:
void foo ()
{
PRINT("foo() starts\n");
...
}
#define macros are simply replaced, literally, by their replacement text during preprocessing. If there is no replacement text, then ... they're replaced by nothing! So this source code:
#define FOO(x)
print(FOO(hello world));
will be preprocessed into just this:
print();
This can be useful to get rid of things you don't want, like, say, assert(). It's mainly useful in conditional situations, where under some conditions there's a non-empty body, though.
As you can see in the above responses, it can be useful when debugging your code.
#ifdef DEBUG
#define debug(msg) fputs(__FILE__ ":" (__LINE__) " - " msg, stderr)
#else
#define debug(msg)
#endif
So, when you are debugging, the function will print the line number and file name so you know if there is an error. And if you are not debugging, it will just produce no output
There are many uses for such a thing.
For example, one is for the macro to have different behavior in different builds. For example, if you want debug messages, you could have something like this:
#ifdef _DEBUG
#define DEBUG_LOG(X, ...) however_you_want_to_print_it
#else
#define DEBUG_LOG(X, ...) // nothing
#endif
Another use could be to customize your header file based on your system. This is from my mesa-implemented OpenGL header in linux:
#if !defined(OPENSTEP) && (defined(__WIN32__) && !defined(__CYGWIN__))
# if defined(__MINGW32__) && defined(GL_NO_STDCALL) || defined(UNDER_CE) /* The generated DLLs by MingW with STDCALL are not compatible with the ones done by Microsoft's compilers */
# define GLAPIENTRY
# else
# define GLAPIENTRY __stdcall
# endif
#elif defined(__CYGWIN__) && defined(USE_OPENGL32) /* use native windows opengl32 */
# define GLAPIENTRY __stdcall
#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 303
# define GLAPIENTRY
#endif /* WIN32 && !CYGWIN */
#ifndef GLAPIENTRY
#define GLAPIENTRY
#endif
And used in header declarations like:
GLAPI void GLAPIENTRY glClearIndex( GLfloat c );
GLAPI void GLAPIENTRY glClearColor( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha );
GLAPI void GLAPIENTRY glClear( GLbitfield mask );
...
(I removed the part for GLAPI)
So you get the picture, a macro that is used in some cases and not used in other cases could be defined to something on those cases and nothing to those other cases.
Other cases could be as follows:
If the macro doesn't take parameters, it could be just to declare some case. A famous example is to guard header files. Another example would be something like this
#define USING_SOME_LIB
and later could be used like this:
#ifdef USING_SOME_LIB
...
#else
...
#endif
Could be that the macro was used at some stage to do something (for example log), but then on release the owner decided the log is not useful anymore and simply removed the contents of the macro so it becomes empty. This is not recommended though, use the method I mentioned in the very beginning of the answer.
Finally, it could be there just for more explanation, for example you can say
#define DONT_CALL_IF_LIB_NOT_INITIALIZED
and you write functions like:
void init(void);
void do_something(int x) DONT_CALL_IF_LIB_NOT_INITIALIZED;
Although this last case is a bit absurd, but it would make sense in such a case:
#define IN
#define OUT
void function(IN char *a, OUT char *b);