Is there an easier way than using #ifdef in C? [duplicate] - c

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);

Related

How to elegantly fix this unused variable warning?

I'm working on some C code that does lot's of error reporting and logging when a DEBUG flag is set, which sometimes produces unused variable warnings when compiling with the DEBUG flag not set.
#ifdef DEBUG
#define CHECK(expr) foo(expr)
#else
#define CHECK(expr)
#endif /* DEBUG */
int x = bar(a, b, c); /* bar has to be called for both DEBUG begin defined and undefined */
CHECK(x == SOME_VALUE); /* Produces an "unused variable" warning if DEBUG is undefined
Edit: Just a little reminder (not sure if it is of any consequence): the argument for the CHECK macro is an expression, not a single variable.
For this pattern, what is the best way to get rid of the unused variable warning?
What I tried/though of:
#ifdef DEBUG
int x = bar(a, b, c);
#else
bar(a, b, c);
#endif
CHECK(x == SOME_VALUE);
and then, to avoid writing the call to bar (which is more complicated in the actual call) twice:
#ifdef DEBUG
int x =
#endif
bar(a, b, c);
CHECK(x == SOME_VALUE);
However, I feel like this is not exactly a clean and readable solution. Is there a better way? Note that for performance reasons the CHECK(expr) macro should not produce any code if DEBUG is undefined (EDIT: and thus, expr should not be evaluated).
Is there a more elegant way than the one I outlined above?
#ifdef DEBUG
#define CHECK(x) x
#else
#define CHECK(x) ((void)sizeof((void)(x),0))
#endif
I think this addresses all of the possible issues :
sizeof ensures that the expression is not evaluated at all, so its side-effects don't happen. That is to be consistent with the usual behaviour of debug-only constructs, such as assert.
((x), 0) uses the comma operator to swallow the actual type of (x). This is to prevent VLAs from triggering evaluation.
(void) explicitly ignores the result of (x) and sizeof so no "unused value" warning appears.
If I understood your question correctly, you can do something like
#ifdef DEBUG
.
.
#else
#define CHECK(expr) ((void)(expr))
#endif /* DEBUG */
to get rid of the warning.
With this solution there is no need for an intermediate variable.
#define DEBUG
#define DOCHECK(a) printf("DOCHECK %d\n", a)
#ifndef DEBUG
#define CHECK(a, b) a
#else
#define CHECK(a, b) do {int x = a; DOCHECK(x == b);} while (0)
#endif
int bar(int x, int y)
{
return x+y;
}
int main()
{
CHECK(bar(2,3), 2+3);
return 0;
}

How to Get Emacs to Properly Handle C Preprocessor Conditionals

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.

Macro to turn off printf statements

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.

Printing name and value of a macro

I have a C program with a lot of optimizations that can be enabled or disabled with #defines. When I run my program, I would like to know what macros have been defined at compile time.
So I am trying to write a macro function to print the actual value of a macro. Something like this:
SHOW_DEFINE(X){\
if( IS_DEFINED(X) )\
printf("%s is defined and as the value %d\n", #X, (int)X);\
else\
printf("%s is not defined\n", #X);\
}
However I don't know how to make it work and I suspect it is not possible, does anyone has an idea of how to do it?
(Note that this must compile even when the macro is not defined!)
As long as you are willing to put up with the fact that SOMESTRING=SOMESTRING indicates that SOMESTRING has not been defined (view it as the token has not been redefined!?!), then the following should do:
#include <stdio.h>
#define STR(x) #x
#define SHOW_DEFINE(x) printf("%s=%s\n", #x, STR(x))
#define CHARLIE -6
#define FRED 1
#define HARRY FRED
#define NORBERT ON_HOLIDAY
#define WALLY
int main()
{
SHOW_DEFINE(BERT);
SHOW_DEFINE(CHARLIE);
SHOW_DEFINE(FRED);
SHOW_DEFINE(HARRY);
SHOW_DEFINE(NORBERT);
SHOW_DEFINE(WALLY);
return 0;
}
The output is:
BERT=BERT
CHARLIE=-6
FRED=1
HARRY=1
NORBERT=ON_HOLIDAY
WALLY=
Writing a MACRO that expands to another MACRO would require the preprocessor to run twice on it.
That is not done.
You could write a simple file,
// File check-defines.c
int printCompileTimeDefines()
{
#ifdef DEF1
printf ("defined : DEF1\n");
#else // DEF1
printf ("undefined: DEF1\n");
#endif // DEF1
// and so on...
}
Use the same Compile Time define lines on this file as with the other files.
Call the function sometime at the start.
If you have the #DEFINE lines inside a source file rather than the Makefile,
Move them to another Header file and include that header across all source files,
including this check-defines.c.
Hopefully, you have the same set of defines allowed across all your source files.
Otherwise, it would be prudent to recheck the strategy of your defines.
To automate generation of this function,
you could use the M4 macro language (or even an AWK script actually).
M4 becomes your pre-pre-processor.
#ifdef MYMACRO
printf("MYMACRO defined: %d\r\n", MYMACRO);
#endif
I don't think what you are trying to do is possible. You are asking for info at runtime which has been processed before compilation. The string "MYMACRO" means nothing after CPP has expanded it to its value inside your program.
You did not specify the compiler you were using. If this is gcc, gcc -E may help you, as it stops after the preprocessing stage, and prints the preprocessing result. If you diff a gcc -E result with the original file, you may get part of what you want.
Why not simply testing it with the preprocessor ?
#if defined(X)
printf("%s is defined and as the value %d\n", #X, (int)X);
#else
printf("%s is not defined\n", #X);
#endif
One can also embed this in another test not to print it everytime:
#if define(SHOW_DEFINE)
#if defined(X)
printf("%s is defined and as the value %d\n", #X, (int)X);
#else
printf("%s is not defined\n", #X);
#endif
#endif
Wave library from boost can be helpful also to do what you want. If your project is big enough, I think it is worth trying. It is a C++ preprocessor, but they are the same any way :)
I believe what you are trying to do is not possible. If you are able to change the way your #defines work, then I suggest something like this:
#define ON 1
#define OFF 2
#define OPTIMIZE_FOO ON
#define OPTIMIZE_BAR OFF
#define SHOW_DEFINE(val)\
if(val == ON) printf(#val" is ON\n");\
else printf(#val" is OFF\n");
It is not possible indeed, the problem being the "not defined" part. If you'd relied on the macro values to activate/deactivate parts of your code, then you could simply do:
#define SHOW_DEFINE(X) \
do { \
if (X > 0) \
printf("%s %d\n", #X, (int)X); \
else \
printf("%s not defined\n", #X); \
} while(0)
Based on Chrisharris, answer I did this.
Though my answer is not very nice it is quite what I wanted.
#define STR(x) #x
#define SHOW_DEFINE(x) printf("%s %s\n", #x, strcmp(STR(x),#x)!=0?"is defined":"is NOT defined")
Only bug I found is the define must not be #define XXX XXX (with XXX equals to XXX).
This question is very close from Macro which prints an expression and evaluates it (with __STRING). Chrisharris' answer is very close from the answer to the previous question.
you can use an integer variable initialized to 1.
multiply the #define with this variable and print the value of variable.

Can you #define a comment in C?

I'm trying to do a debug system but it seems not to work.
What I wanted to accomplish is something like this:
#ifndef DEBUG
#define printd //
#else
#define printd printf
#endif
Is there a way to do that? I have lots of debug messages and I won't like to do:
if (DEBUG)
printf(...)
code
if (DEBUG)
printf(...)
...
No, you can't. Comments are removed from the code before any processing of preprocessing directives begin. For this reason you can't include comment into a macro.
Also, any attempts to "form" a comment later by using any macro trickery are not guaranteed to work. The compiler is not required to recognize "late" comments as comments.
The best way to implement what you want is to use macros with variable arguments in C99 (or, maybe, using the compiler extensions).
A common trick is to do this:
#ifdef DEBUG
#define OUTPUT(x) printf x
#else
#define OUTPUT(x)
#endif
#include <stdio.h>
int main(void)
{
OUTPUT(("%s line %i\n", __FILE__, __LINE__));
return 0;
}
This way you have the whole power of printf() available to you, but you have to put up with the double brackets to make the macro work.
The point of the double brackets is this: you need one set to indicate that it's a macro call, but you can't have an indeterminate number of arguments in a macro in C89. However, by putting the arguments in their own set of brackets they get interpreted as a single argument. When the macro is expanded when DEBUG is defined, the replacement text is the word printf followed by the singl argument, which is actually several items in brackets. The brackets then get interpreted as the brackets needed in the printf function call, so it all works out.
С99 way:
#ifdef DEBUG
#define printd(...) printf(__VA_ARGS__)
#else
#define printd(...)
#endif
Well, this one doesn't require C99 but assumes compiler has optimization turned on for release version:
#ifdef DEBUG
#define printd printf
#else
#define printd if (1) {} else printf
#endif
On some compilers (including MS VS2010) this will work,
#define CMT / ## /
but no grantees for all compilers.
You can put all your debug call in a function, let call it printf_debug and put the DEBUG inside this function.
The compiler will optimize the empty function.
The standard way is to use
#ifndef DEBUG
#define printd(fmt, ...) do { } while(0)
#else
#define printd(fmt, ...) printf(fmt, __VA_ARGS__)
#endif
That way, when you add a semi-colon on the end, it does what you want.
As there is no operation the compiler will compile out the "do...while"
Untested:
Edit: Tested, using it by myself by now :)
#define DEBUG 1
#define printd(fmt,...) if(DEBUG)printf(fmt, __VA_ARGS__)
requires you to not only define DEBUG but also give it a non-zer0 value.
Appendix:
Also works well with std::cout
In C++17 I like to use constexpr for something like this
#ifndef NDEBUG
constexpr bool DEBUG = true;
#else
constexpr bool DEBUG = false;
#endif
Then you can do
if constexpr (DEBUG) /* debug code */
The caveats are that, unlike a preprocessor macro, you are limited in scope. You can neither declare variables in one debug conditional that are accessible from another, nor can they be used at outside function scopes.
You can take advantage of if. For example,
#ifdef debug
#define printd printf
#else
#define printd if (false) printf
#endif
Compiler will remove these unreachable code if you set a optimization flag like -O2. This method also useful for std::cout.
As noted by McKay, you will run into problems if you simply try to replace printd with //. Instead, you could use variadric macros to replace printd with a function that does nothing as in the following.
#ifndef DEBUG
#define printd(...) do_nothing()
#else
#define printd(...) printf(__VA_ARGS__)
#endif
void do_nothing() { ; }
Using a debugger like GDB might help too, but sometimes a quick printf is enough.
I use this construct a lot:
#define DEBUG 1
#if DEBUG
#if PROG1
#define DEBUGSTR(msg...) { printf("P1: "); printf( msg); }
#else
#define DEBUGSTR(msg...) { printf("P2: "); printf( msg); }
#endif
#else
#define DEBUGSTR(msg...) ((void) 0)
#endif
This way I can tell in my console which program is giving which error message... also, I can search easily for my error messages...
Personally, I don't like #defining just part of an expression...
It's been done. I don't recommend it. No time to test but the mechanism is kind of like this:
#define printd_CAT(x) x ## x
#ifndef DEBUG
#define printd printd_CAT(/)
#else
#define printd printf
#endif
This works if your compiler processes // comments in the compiler itself (there's no guarantee like the ANSI guarantee that there are two passes for /* comments).

Resources