I want to print info only if _DEBUG is defined
#define DEBUG(y) y == true ? #define _DEBUG true : #define _DEBUG false
#ifdef _DEBUG
#define Print(s) printf(s);
#endif
Getting Error:
error: '#' is not followed by a macro parameter
Any suggestion how to achieve this with pre-processor directives?
I intend to use it from my main as:
DEBUG(true);
Print("Inside main in debug mode");
You cannot redefine a MACRO at run-time.
Neither you can have a #define inside of another #define, like you try in the first line of your code.
You can do something like this:
#ifdef _DEBUG
#define Print(s) printf("%s", s)
#else
#define Print(s)
#endif
And use it from your main as:
#define _DEBUG
Print("Inside main in debug mode");
#undef _DEBUG
Print("Inside main debug mode off");
If you really need to switch debug on and off at run-time, your can do something like this:
void PrintIf(BOOL dbg, char * msg)
{
if (dbg)
{
printf("%s", msg)
}
}
And use it like this
y = TRUE;
PrintIf(y,"Inside main in debug mode");
y = FALSE;
PrintIf(y,"Inside main debug mode off");
Try this:
#ifdef DEBUG
#define Print(s) printf("%s", s)
#else
#define Print(s)
#endif
Then:
#define DEBUG
Print("Inside main in debug mode");
I intend to use it from my main as:
DEBUG(y);
Print("Inside main in debug mode");
Sorry, but ifdef are compile time (not run-time). You could use a global bool and runtime checking to enable and disable debug.
You can't create preprocessor statements with macros as you are trying to do; it doesn't work and isn't allowed. For conditional printing, see C #define macro for debug printing.
The problem occurs here:
#define DEBUG(y) y == true ? #define _DEBUG true : #define _DEBUG false
When introducing #defines, the definition # occurs at the beginning of the line, not later (although) preprocessors generally allow one or two line indents.) You need to rewrite your #define eliminating the ternary operator simply as:
#ifdef _DEBUG
#define Print(s) printf(s);
#endif
While you may extend you defines with macros, you often introduce additional errors. It is generally better to stick to wrapping your _DEBUG code simply in #ifdef statements:
#ifdef _DEBUG
fprintf (stderr, "your error messages\n"); // using standard printf/fprintf instead of macros
...
#endif /* _DEBUG */
Macros are substituted at preprocessing stage and
#define DEBUG(y) y == true ? #define _DEBUG true : #define _DEBUG false
this statement will be evaluated at compile time.
Conditional operator (ternary operator) are evaluated at compile time. So you are getting this error and # operator must always be used at the beginning of the statement that is the second mistake you are doing.
You can better use it this way
#define DEBUG
printf ("true");
#else
printf ("false");
You can also define this macro dynamically by using the gcc option -D
gcc -D DEBUG filename.c -o outputFile
The first line is incorrect:
#define DEBUG(y) y == true ? #define _DEBUG true : #define _DEBUG false
You cannot use #define inside preprocessor directive (like another #define)
And it does not make sense, since preprocessing happens before the real compilation (so before run time, when your y has some value). Read the cpp preprocessor documentation. Recall that sometimes the preprocessor is even a different program (/lib/cpp) but is today the first phase of most C compilers.
You could ask for the preprocessed form of your source code (e.g. with gcc -C -E source.c > source.i if using GCC) and look at that form with a pager (less source.i) or your editor.
Related
I want to insert some debug output statements into a big C code base. These debug output statements will be controlled by a compiler option switch.
The debug output statement looks like this:
#ifdef DEBUG_FLAG
Print(someSymbol)
#endif
To save some typing , I am wondering if it is possible to define a simple macro that expands to above debug output statement block?
For example:
#define DBG_MACRO(someSymbol) (something that can expand to above)
You cannot put preprocessor directives inside a preprocessor macro.
However, nothing stops you from defining a macro which expands to nothing:
#ifdef DEBUG_FLAG
# define Print(x) Print(x)
#else
# define Print(x)
#endif
// Expands to an empty statement if DEBUG_FLAG were not set and
// to a call to Print(something) if DEBUG_FLAG were set.
Print(something);
The above depends on Print being a function which has already been declared/defined. If the macro is defined with DEBUG_FLAG set, the macro is "replaced" with itself, but C preprocessor expansions are not recursive so the expansion only happens once, resulting in a call to Print.
It is not possible to do it that way; however, it is easy to conditionally define a macro:
#ifdef DEBUG_FLAG
#define DBG_MACRO(arg) Print(arg)
#else
#define DBG_MACRO(arg)
#endif
It is better to make a DB macro that can handle many debug statements.
Then you can quickly surround ANY optional debug code with these 4 chars: DB( )
Here's the macro:
#define DEBUG true // or false
#ifdef DEBUG
#define DB(arg) { arg }
#else
#define DB(arg)
#endif
// Example uses:
DB(Serial.begin (9600);)
DB(if (!bLastRadarMotion)
Serial.println("New Motion");)
DB(Serial.print("Room just became UN-Occupied after ");
Serial.print(stillSecondsThreshold);
Serial.println(" seconds.");)
DB(
Serial.print("Room just became UN-Occupied after ");
Serial.print(stillSecondsThreshold);
Serial.println(" seconds.");
)
What does the following statement mean:
#define FAHAD
I am familiar with the statements like:
#define FAHAD 1
But what does the #define statement without a token signify?
Is it that it is similar to a constant definition?
Defining a constant without a value acts as a flag to the preprocessor, and can be used like so:
#define MY_FLAG
#ifdef MY_FLAG
/* If we defined MY_FLAG, we want this to be compiled */
#else
/* We did not define MY_FLAG, we want this to be compiled instead */
#endif
it means that FAHAD is defined, you can later check if it's defined or not with:
#ifdef FAHAD
//do something
#else
//something else
#endif
Or:
#ifndef FAHAD //if not defined
//do something
#endif
A real life example use is to check if a function or a header is available for your platform, usually a build system will define macros to indicate that some functions or headers exist before actually compiling, for example this checks if signal.h is available:
#ifdef HAVE_SIGNAL_H
# include <signal.h>
#endif/*HAVE_SIGNAL_H*/
This checks if some function is available
#ifdef HAVE_SOME_FUNCTION
//use this function
#else
//else use another one
#endif
Any #define results in replacing the original identifier with the replacement tokens. If there are no replacement tokens, the replacement is empty:
#define DEF_A "some stuff"
#define DEF_B 42
#define DEF_C
printf("%s is %d\n", DEF_A, DEF_B DEF_C);
expands to:
printf("%s is %d\n", "some stuff", 42 );
I put a space between 42 and ) to indicate the "nothing" that DEF_C expanded-to, but in terms of the language at least, the output of the preprocessor is merely a stream of tokens. (Actual compilers generally let you see the preprocessor output. Whether there will be any white-space here depends on the actual preprocessor. For GNU cpp, there is one.)
As in the other answers so far, you can use #ifdef to test whether an identifier has been #defined. You can also write:
#if defined(DEF_C)
for instance. These tests are positive (i.e., the identifier is defined) even if the expansion is empty.
#define FAHAD
this will act like a compiler flag, under which some code can be done.
this will instruct the compiler to compile the code present under this compiler option
#ifdef FAHAD
printf();
#else
/* NA */
#endif
I regularly use object-like preprocessor macros as boolean flags in C code to turn on and off sections of code.
For example
#define DEBUG_PRINT 1
And then use it like
#if(DEBUG_PRINT == 1)
printf("%s", "Testing");
#endif
However, it comes a problem if the header file that contains the #define is forgotten to be included in the source code. Since the macro is not declared, the preprocessor treats it as if it equals 0, and the #if statement never runs.
When the header file is forgotten to be included, non-expected, unruly behaviour can occur.
Ideally, I would like to be able to both check that a macro is defined, and check that it equals a certain value, in one line. If it is not defined, the preprocessor throws an error (or warning).
I'm looking for something along the lines of:
#if-def-and-true-else-throw-error(DEBUG_PRINT)
...
#endif
It's like a combination of #ifdef and #if, and if it doesn't exist, uses #error.
I have explored a few avenues, however, preprocessor directives can't be used inside a #define block, and as far as I can tell, there is no preprocessor option to throw errors/warnings if a macro is not defined when used inside a #if statement.
This may not work for the general case (I don't think there's a general solution to what you're asking for), but for your specific example you might consider changing this sequence of code:
#if(DEBUG_PRINT == 1)
printf("%s", "Testing");
#endif
to:
if (DEBUG_PRINT == 1) {
printf("%s", "Testing");
}
It's no more verbose and will fail to compile if DEBUG_PRINT is not defined or if it's defined to be something that cannot be compared with 1.
as far as I can tell, there is no preprocessor option to throw errors/warnings if a macro is not defined when used inside a #if statement.
It can't be an error because the C standard specifies that behavior is legal. From section 6.10.1/3 of ISO C99 standard:
After all replacements due to macro expansion and the defined unary
operator have been performed, all remaining identifiers are replaced with the pp-number
0....
As Jim Balter notes in the comment below, though, some compilers (such as gcc) can issue warnings about it. However, since the behavior of substituting 0 for unrecognized preprocessor tokens is legal (and in many cases desirable), I'd expect that enabling such warnings in practice would generate a significant amount of noise.
There's no way to do exactly what you want. If you want to generate a compilation failure if the macro is not defined, you'll have to do it explicitly
#if !defined DEBUG_PRINT
#error DEBUG_PRINT is not defined.
#endif
for each source file that cares. Alternatively, you could convert your macro to a function-like macro and avoid using #if. For example, you could define a DEBUG_PRINT macro that expands to a printf call for debug builds but expands to nothing for non-debug builds. Any file that neglects to include the header defining the macro then would fail to compile.
Edit:
Regarding desirability, I have seen numerous times where code uses:
#if ENABLE_SOME_CODE
...
#endif
instead of:
#ifdef ENABLE_SOME_CODE
...
#endif
so that #define ENABLE_SOME_CODE 0 disables the code rather than enables it.
Rather than using DEBUG_PRINT directly in your source files, put this in the header file:
#if !defined(DEBUG_PRINT)
#error DEBUG_PRINT is not defined
#endif
#if DEBUG_PRINT
#define PrintDebug([args]) [definition]
#else
#define PrintDebug
#endif
Any source file that uses PrintDebug but doesn't include the header file will fail to compile.
If you need other code than calls to PrintDebug to be compiled based on DEBUG_PRINT, consider using Michael Burr's suggestion of using plain if rather than #if (yes, the optimizer will not generate code within a false constant test).
Edit:
And you can generalize PrintDebug above to include or exclude arbitrary code as long as you don't have commas that look like macro arguments:
#if !defined(IF_DEBUG)
#error IF_DEBUG is not defined
#endif
#if IF_DEBUG
#define IfDebug(code) code
#else
#define IfDebug(code)
#endif
Then you can write stuff like
IfDebug(int count1;) // IfDebug(int count1, count2;) won't work
IfDebug(int count2;)
...
IfDebug(count1++; count2++;)
Yes you can check both:
#if defined DEBUG && DEBUG == 1
# define D(...) printf(__VA_ARGS__)
#else
# define D(...)
#endif
In this example even when #define DEBUG 0 but it is not equal to 1 thus nothing will be printed.
You can do even this:
#if defined DEBUG && DEBUG
# define D(...) printf(__VA_ARGS__)
#else
# define D(...)
#endif
Here if you #define DEBUG 0 and then D(1,2,3) also nothing will be printed
DOC
Simply create a macro DEBUG_PRINT that does the actual printing:
#define DEBUG_PRINT(n, str) \
\
if(n == 1) \
{ \
printf("%s", str); \
} \
else if(n == 2) \
{ \
do_something_else(); \
} \
\
#endif
#include <stdio.h>
int main()
{
DEBUG_PRINT(1, "testing");
}
If the macro isn't defined, then you will get a compiler error because the symbol is not recognized.
#if 0 // 0/1
#define DEBUG_PRINT printf("%s", "Testing")
#else
#define DEBUG_PRINT printf("%s")
#endif
So when "if 0" it'll do nothing and when "if 1" it'll execute the defined macro.
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).
I'm trying to have a debugging mode on so if
#define DEBUG 1
I want to printf some variable values and if
#define DEBUG 0
I want them off.
The problem is I have many implementation files and I want this DEBUG variable to be available for the whole project. Right now I need to edit the DEBUG variable in foo1.c, foo2.c, foo3.c which seems tedious and error-prone and there must be a better way. Any suggestions?
When compiling, you should be able to specify an option to your compiler. For example, you can call GCC with the -DDEBUG option.
In this case, you would be better using:
#ifdef DEBUG
#endif
or:
#if defined(DEBUG)
#endif
if this is not the way you're doing it now. I'm surprised that you don't have a global header file for your project. Something along the lines of:
#undef DEBUG
#define DEBUG 1
in a file called "debug.h". In your C programs, you can include this by using #include "debug.h"
Try something like Steve McConnel suggests in section 6 of "Chapter 8: Defensive Programming" from Code Complete 2... Add this to your code:
#ifdef DEBUG
#if (DEBUG > 0) && (DEBUG < 2)
printf("Debugging level 1");
#endif
#if (DEBUG > 1) && (DEBUG < 3)
printf("Debugging level 2");
#endif
#if (DEBUG > n-1) && (DEBUG < n)
printf("Debugging level n");
#endif
#endif
Then when you compile, add this flag (warning: This might be compiler-dependent):
-DDEBUG=m
Or, have a global header that defines these sorts of things, as others have suggested.
As a response to your problem you can also simply invoke the compiler like:
cc -c -DDEBUG=1
or
cc -c -DDEBUG=0
You must delete the "define DEBUG 1/0" in your files - or replace it with:
#ifndef DEBUG
#define DEBUG 0
#endif
Here is what I am using (GCC syntax):
create a file debug.h with the following content and include it in each c file:
#ifdef DEBUG
extern FILE *dbgf;
#define D_MIN 0x00010000 // Minimum level
#define D_MED 0x00020000 // Medium level
#define D_MAX 0x00040000 // Maximum level
#define D_FLUSH 0x00080000 // Usefull by a program crash
#define D_TRACE 0x00100000
#define D_1 0x00000001
...
#define D(msk, fmt, args...) if(msk & dbgmsk) { fprintf(dbgf, "%s:",__FUNCTION__); fprintf(dbgf, fmt, ## args ); if(msk & D_FLUSH) fflush(dbgf); }
#define P(msk, fmt, args...) if(msk & dbgmsk) { fprintf(dbgf, fmt, ## args ); if(msk & D_FLUSH) fflush(dbgf); }
#else
#define D(msk, fmt, args...)
#define P(msk, fmt, args...)
#endif
dbgmsk is variable, which can be global (whole program) or local/static and must be initialized a start. You can define several options for the whole program or for each module. This is better and more flexible than the version with the level variable.
Ex.
module1.c:
#include "debug.h"
static int dbgmsk; // using local dbgmsk
module1_setdbg(int msk) { dbgmsk = msk; D(D_TRACE,"dbgmsk1=%x\n", dbgmsk); }
foo1() { P(D_1, "foo1 function\n" );
....
}
foo2() {}
...
foo3.c
#include "debug.h"
extern int dbgmsk; // using global dbgmsk
Ex. main:
#include "debug.h"
FILE *dbgf;
int dbgmsk = 0; // this is the global dbgmsk
int main() {
dbgf = stderr; // or your logfile
dbgmsk = D_MIN;
module1_setdbg(D_MIN|D_MED|D_TRACE|D_1);
....
}
I'm also storing all dbgmsk variables in a config text file that is read at the program start.
As #person-b says, specify this define as a compiler option, e.g. -D DEBUG
Note though that to simplify this you should change the test in your code from:
#if DEBUG
to:
#ifdef DEBUG
This way you don't have to worry about specifying a 0 or 1 value but can instead rely on it being defined or not.
Put the "#define DEBUG" in "debug.h" and #include that header file in each *.c file.
The suggestion from samoz and Stephen Doyle to check for the existence of a definition for DEBUG rather than its value is a good one. However, if you really want to use DEBUG=0, this is how you can do it: Each time you define the DEBUG flag (i.e., in each file), check for an existing definition:
#ifndef DEBUG
#define DEBUG 1
#endif
Then, when you use the option -DDEBUG=0 with your compiler, the #define line will never be executed.
Try this instead.
In the first file you have that will be included:
#define DEBUG
Then whenever you want to have debug code, do this:
#ifdef DEBUG
do some stuff
#endif
This will also prevent your debugging code from making it into release code.
I personally like
#ifdef DEBUG
#define IFDEBUG if(0)else
#else
#define IFDEBUG if(1)else
#endif