I have a performance sensitive CUDA code, which I'm using
#ifdef DEBUG_<NAME_OF_SECTION>
...
#else
...
#endif
...conditionals to encapsulate speed-crippling debugging code, which grabs extra info off the GPU.
Everything goes well in emacs (Centos 6.0) up until the #else.
This deindents (by 1 tab) the text inside the else clause of the preprocessor conditional and continues to deindent everything afterwards.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Note:
) replication inside preprocessor conditionals seems to be properly handled by the C-mode. But ); duplication breaks things, forcing you to move the ); outside the conditional ... oh dear how inconsistent. I'm keeping this question open until we get proper elisp code to fix this inconsistency.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NOTE on current answer:
Jens has provided inaccurate information in claiming that indenting nested ) inside conditionals is "impossible". It is not only possible, but Emacs' C-Mode actively does this. Note the proper indentation of the example c program at the end of this question post for proof of that. So it would stand to reason that ); is also feasible to indent, though caution should be exercised for the reasons outlined by Jens.
Anyhow, I want to make sure people see that statement is incorrect, so they do not think this question is unanswerable. I will remove this comment and my downvote on Jens' post when he amends his inaccurate statements to reflect that it is possible, is implemented in C-mode for the very case of ) he outlines, but is not recommended.
Currently I'm resorting to manually respacing things forward one tab, but it's wasting a lot of time (the code is long).
Any idea what I can add to my ~/.emacs file to fix this???
Thanks in advance!
EDIT 1
I should mention that the clause it seems to be choking on is a function closing, e.g.
MyFunc<<<Blk,Thr>>>(Stuff1,
#ifdef DEBUG_FUNC1
Stuff2,
dev_Debug);
#else
Stuff2); //Deindents here.
#endif
//Everything here on out is deindented.
It may be a specific failure on that kind of code structure...
EDIT 2
Here's a simply C code version... the code works as expected, but not the deindent on the last #else clause...
#include <stdio.h>
//#define DEBUG
void printer
(int A,
#ifdef DEBUG
int B,
int C)
#else
int B)
#endif
{
#ifdef DEBUG
printf("A: %i, B: %i, C: %i\n", A, B, C);
#else
printf("A: %i, B: %i\n", A, B);
#endif
}
int main()
{
int A = -3;
int B = 1;
int C = 3;
printer(A,
#ifdef DEBUG
B,
C);
#else
B);
#endif
return 0;
}
...that's along the lines of what I'm doing. I know it works syntactically in C (or at least I think does... it gives correct results), however emacs doesn't like that #else clause inside the function call....
I think the problem is in the logic of your code. Logically you have different parameters in a function parameter list. The closing parenthesis should not be part of the conditional.
MyFunc<<<Blk,Thr>>>(
Stuff1,
#ifdef DEBUG_FUNC1
Stuff2,
dev_Debug
#else
Stuff2
#endif
);
Or alternatively you should have two complete versions of the prototype that are chosen according to your debug macro. Everthing else is not only difficult to parse for emacs (or probably any other editor) but also for the poor human that comes after you.
What you want is not possible since the indentation level of a code might depend on the macros:
#if A
(
#endif
something
#if B
)
#endif
where A and B are the same for all valid compilations. Emacs can't know without assuming values for A and B, how to indent.
Related
I'm trying to create transparent debug prtinf functions into OpenCL kernels that:
Do not pollute the code (can be called from max one line).
Compile away should the designated preprocessor condition prove to be untrue.
Problem is, that printf is a variadic function and I cannot wrap it in a variadic macro, since OpenCL kernel language (C99 derivate) does not support variadic macros.
#if DEBUG_CONDITION
printf("Any int %d\n",i);
#endif
Would work but would quickly render the code unreadable.
if(DEBUG_CONDITION) printf("Any int %d\n",i);
This would also work, but would require me to enable the printf pragmas, because the functions need are actually referenced in the code, even though I know they will be compiled away. (From OpenCL 2.0 on, printf will have defined sync properties, and one cannot know for sure whether the sync semantics are introduced into the binary prior to actually removing the functions or not.)
PRINTF("Any int %d\n",i);
I'm looking for something like this (or similar) that looks nice, but can fully neglect the referencing of prtintf alltogether.
As Kerrek SB has already suggested in his comment:
#if DEBUG_CONDITION
#define PRINTF(args) printf args
#else
#define PRINTF(args)
#fi
and use it as
PRINTF(("Debugging i: %d", i ));
Thanks to the double paranthesis it's no variadic macro.
If you can't use variadic macros then why not a variadic function (which is part of the C standard)
#ifdef NDEBUG
inline int debug_print(char *fmt, ...)
{}
#else
int debug_print(char *fmt, ...)
{
/* implement this I'm too lazy */
}
#endif
This results in an extra function call as opposed to a macro (though perhaps it can be inlined) but this shouldn't matter as it only happens when you are calling a debug statement (so who cares about the performance then)
What MACRO can be used to switch off printf statements, rather than removing them all for deployment builds, I just want to switch them off, skip them, ignore them.
EDIT: I personally use gcc, but code is part of a larger project which will be compiled on a Panda board running Ubuntu.
Not exactly what you ask for, but I use this construct in my code for debug output when I do not have a proper logging system handy:
#if 1
#define SPAM(a) printf a
#else
#define SPAM(a) (void)0
#endif
So I can do this all over my code
SPAM(("foo: %d\n", 42));
and then disable all of them by changing 1 to 0 in #if above.
But if you have variadic macro support in all compilers that you write code for, then you may go for other answers and just redefine printf. (That being said, I find it useful to distinct debugging prints from regular ones in code — using a different function name helps readability.)
Note that you also can redirect stdout to the /dev/null, but I assume that you want to get rid from runtime overhead as well.
#ifdef IGNORE_PRINTF
#define printf(fmt, ...) (0)
#endif
See also C #define macro for debug printing which discusses some important issues closely related to this.
Two options, either:
#define printf(...)
(requires C99 variadic macro parameters), you need to put it in some common header file which is never included before stdio.h, if there is one..
Or you can tell the linker to link it to something else, in GCC you would define
int wrap_printf(void) {return 0;}
and link using
--wrap printf
All that said, you should probably not be using printf for printing debug output, but rather a macro or utility function (which in turn can use printf if you'd like) which you have better control over.
Hope that helps.
If you want to avoid the potential warning that Jonathan's answer may give you and if you don't mind an empty call to printf you could also do something like
#define printf(...) printf("")
This works because C macros are not recursive. The expanded printf("") will just be left as such.
Another variant (since you are using gcc) would be something like
inline int ignore_printf(char const*, ...)
__attribute__ ((format (printf, 1, 2)));
inline int ignore_printf(char const*, ...) { return 0; }
#define printf ignore_printf
and in one compilation unit
int ignore_printf(char const*, ...)
I use to prefix the debug printf()s (not all of them) with PDEB.
For the debug builds, I compile with -DPDEB= (nothing)
For the release builds, I compile with -DPDEB="0&&" or -DPDEB="0 && "
That way, the following code (test.c):
#include <stdio.h>
void main(void) {
printf("normal print\n");
PDEB printf("debug print\n");
}
outputs:
either (in release mode):
normal print
either (in debug mode):
normal print
debug print
Ideally, one could aim for turning the PDEB into the "//" (comments mark), except that this is not possible under the standard pre-/processing chain.
Another possibility would be something like freopen("/dev/null", "w", stdout);
This doesn't exactly disable printf though -- it's roughly equivalent to running your program with stdout redirected to /dev/null, like: ./myprog > /dev/null at the shell prompt.
I included #define printf // in common header file. It will suppress all the printf.
Below simple function serves the purpose, I use the same.
int printf(const char *fmt, ...)
{
return (0)
}
Use this macro to enable or disable the printf.
//Uncomment the following line to enable the printf function.
//#define ENABLE_PRINTF
#ifdef ENABLE_PRINTF
#define DEBUG_PRINTF(f,...) printf(f,##__VA_ARGS__)
#else
#define DEBUG_PRINTF(f,...)
#endif
Then call "DEBUG_PRINTF" instead of "printf".
For example:
DEBUG_PRINTF("Hello world: %d", whateverCount);
I have used two macros for this. The first one defines the condition to print. In this simple example we print any time the parameter is not zero. More complex expressions can be used.
The second one determines, based on the first macro, to call or not printf.
If the condition can be determined by the compiler (with the right optimization settings) no code is generated.
If the condition cannot be determined at compile time then will be at run time. One of the advantages of this method is that if printf is not going to happen then the whole printf is not evaluated avoiding many conversions to string that can happen in a complex printf statement.
#define need_to_print(flag) ((flag) != 0))
#define my_printf(debug_level, ...) \
({ \
if(need_to_print(debug_level)) \
printf(__VA_ARGS__); \
})
to use it call my_printf instead of printf and add a parameter at the beginning for the print condition.
my_printf(0, "value = %d\n", vv); //this will not print
my_printf(1, "value = %d\n", vv); //this will print
my_printf(print_debug, "value = %d\n", vv); //this will print if print_debug != 0
the ( ... ) parenthesis surrounding the macro make it a single statement.
So, to start off, here's the code, with actual names switched for generic ones to limit confusion.
/* Get the list of Hotkey commands */
#define A_COMMANDS_MACRO(a, b, c, d) a = b ,
enum {
#include "commandsFile.def"
} ;
#undef A_COMMANDS_MACRO
This is a snippet from some source code I have been looking over and considering forking as a way to familiarize myself with the intricacies of the C programming language. So, to my untrained eye, this appears to do nothing. To my brain, defining something and then immediately undefining it would seem to cancel each other out.
Obviously, I realize that I'm wrong. But why am I wrong?
The "commandsFile.def" file probably uses the "A_COMMANDS_MACRO" macro somewhere internally.
Remember that "#include" essentially pastes the included file into the including one, so the #define is still in effect when "commandsFile.def" is processed.
What you see there is usually called X-MACRO. The technique consists in defining macros via #define, and then including a file that makes use of them with #include.
As a very simple example, you could have a header (say myheader.h) that declared 2 functions in the form of:
int foo(MYTYPE a, MYTYPE_PTR b);
void bar(MYTYPE a, MYTYPE_PTR b);
And then, in your code:
#define MYTYPE int
#define MYTYPE_PTR int*
#include "myheader.h"
#undef MYTYPE
#undef MYTYPE_PTR
The #undefs are sometimes in the included file as well.
For more information, take a look at this Wikipedia link.
The commandsFile.def should contain many lines:
A_COMMANDS_MACRO(A_COMMAND, 10, na, na)
A_COMMANDS_MACRO(OTHER_COMMAND, 23, na, na)
So that the code would create an enum with available commands and their codes.
It could be useful when this .def file is used by a program written in other language, so that instead of implementing text parsing, it uses C preprocessor to do this.
In C/C++
What happens to code placed between an #if 0/#endif block?
#if 0
//Code goes here
#endif
Does the code simply get skipped and therefore does not get executed?
Not only does it not get executed, it doesn't even get compiled.
#if is a preprocessor command, which gets evaluated before the actual compilation step. The code inside that block doesn't appear in the compiled binary.
It's often used for temporarily removing segments of code with the intention of turning them back on later.
It's identical to commenting out the block, except with one important difference: Nesting is not a problem. Consider this code:
foo();
bar(x, y); /* x must not be NULL */
baz();
If I want to comment it out, I might try:
/*
foo();
bar(x, y); /* x must not be NULL */
baz();
*/
Bzzt. Syntax error! Why? Because block comments do not nest, and so (as you can see from SO's syntax highlighting) the */ after the word "NULL" terminates the comment, making the baz call not commented out, and the */ after baz a syntax error. On the other hand:
#if 0
foo();
bar(x, y); /* x must not be NULL */
baz();
#endif
Works to comment out the entire thing. And the #if 0s will nest with each other, like so:
#if 0
pre_foo();
#if 0
foo();
bar(x, y); /* x must not be NULL */
baz();
#endif
quux();
#endif
Although of course this can get a bit confusing and become a maintenance headache if not commented properly.
It permanently comments out that code so the compiler will never compile it.
The coder can later change the #ifdef to have that code compile in the program if he wants to.
It's exactly like the code doesn't exist.
I'd like to add on for the #else case:
#if 0
/* Code here will NOT be complied. */
#else
/* Code will be compiled. */
#endif
#if 1
/* Code will be complied. */
#else
/* Code will NOT be compiled. */
#endif
When the preprocessor sees #if it checks whether the next token has a non-zero value. If it does, it keeps the code around for the compiler. If it doesn't, it gets rid of that code so the compiler never sees it.
If someone says #if 0 they are effectively commenting out the code so it will never be compiled. You can think of this the same as if they had put /* ... */ around it. It's not quite the same, but it has the same effect.
If you want to understand what happened in detail, you can often look. Many compilers will allow you to see the files after the preprocessor has run. For example, on Visual C++ the switch /P command will execute the preprocessor and put the results in a .i file.
Lines beginning with a # are preprocessor directives. #if 0 [...] #endif blocks do not make it to the compiler and will generate no machine code.
You can demonstrate what happens with the preprocessor with a source file ifdef.cxx:
#if 0
This code will not be compiled
#else
int i = 0;
#endif
Running gcc -E ifdef.cxx will show you what gets compiled.
You may choose to use this mechanism to prevent a block of code being compiled during the development cycle, but you would probably not want to check it in to your source control as it just adds cruft to your code and reduces readability. If it's a historical piece of code that has been commented out, then it should be removed: source control contains the history, right?
Also, the answer may be the same for both C and C++ but there is no language called C/C++ and it's not a good habit to refer to such a language.
Not quite
int main(void)
{
#if 0
the apostrophe ' causes a warning
#endif
return 0;
}
It shows "t.c:4:19: warning: missing terminating ' character"
with gcc 4.2.4
It is a cheap way to comment out, but I suspect that it could have debugging potential. For example, let's suppose you have a build that output values to a file. You might not want that in a final version so you can use the #if 0... #endif.
Also, I suspect a better way of doing it for debug purpose would be to do:
#ifdef DEBUG
// output to file
#endif
You can do something like that and it might make more sense and all you have to do is define DEBUG to see the results.
This question already has answers here:
#define macro for debug printing in C?
(14 answers)
Closed 5 years ago.
From what I understand assert is a macro in C and supposedly if you use it at compile time but leave it disabled then there won't be overhead (which might not be correct I don't know).
The problem for me is that what I'd like to do is get all the variables passed to my function and print out that output, but only if I want debugging enabled. Here is what I have so far:
int exampleFunction (int a, int b)
{
#ifdef debugmode
printf("a = %i, b = %i", a, b);
#endif
}
I'm wondering if there is any easier (and less ugly) method for doing something like this. xdebug for php has this feature and I've found is saves me an enormous amount of time when debugging so i want to do it for each function.
Thanks
try this:
#ifdef debugmode
#define DEBUG(cmd) cmd
#else
#define DEBUG(cmd)
#endif
DEBUG(printf("a = %i, b = %i", a, b));
now, if you have debugmode defined, you get your print statement. otherwise, it never shows up in the binary.
Using GCC, I really enjoy to add, per file:
#if 0
#define TRACE(pattern,args...) fprintf(stderr,"%s:%s/%u" pattern "\n",__FILE__,__FUNCTION__,__LINE__,##args)
#else
#define TRACE(dummy,args...)
#endif
and then in the code:
i++;
TRACE("i=%d",i);
i will be printed only when I activate the TRACE() macro in the top of the file. Works really great, plus it prints the source file, line and function it occurred.
if (MY_DEBUG_DEFINE) {
do_debug_stuff();
}
Any half decent compiler would optimize the block away. Note you need to define MY_DEBUG_DEFINE as a boolean (ie 0 or not 0).
#define MY_DEBUG_DEFINE defined(NDEBUG)
If you happen to compile with maximum warning level, this trick avoids unreferenced argument.
Workaround to get vararg with preprocessors that don't support it
#define DEBUG
#ifdef DEBUG
#define trace(args) printf args
#else
#define trace(args)
#endif
int dostuff(int value)
{
trace(("%d", value));
}
You can define PRINTF_IF_DEBUGGING as
#ifndef NDEBUG
#define PRINTF_IF_DEBUGGING(X) printf(X)
#else
#define PRINTF_IF_DEBUGGING(X)
#endif
This will centralize the #ifdefs in only one place.
Well, the problem with the PRINT_DEBUG type macros as given here, is that they only allow one parameter. For a proper printf() we'll need several, but C macros don't (presently) allow variable arguments.
So, to pull this off, we've got to get creative.
#ifdef debugmode
#define PRINTF printf
#else
#define PRINTF 1 ? NULL : printf
#endif
Then when you write PRINTF("a = %i, b = %i", a, b);, in non-debug mode, it will be renders as (effectively):
if (true) NULL;
else printf("a = %i, b = %i", a, b);
The compiler is happy, but the printf is never execute, and if the compiler if bright (i.e, any modern C compiler), the code for the printf() will never be generated, as the compiler will recognize that path can never be taken.
Note, however, that the parameters will still be evaluated, so if they have any side effects (i.e, ++x or a function call), they code may be generated (but not executed)
I would also print some other C preprocessor flags that can help you track problems down
printf("%s:%d {a=%i, b=%i}\n", __FILE__, __LINE__, a, b);