C: `Enable debugging messages

This is probably a really stupid question, but how do I include these debugging messages in my code?

#ifdef DEBUG_MSG printf("initial state : %d\n", initial_state); #endif 

Thank you very much in advance,

+4
source share
5 answers

#ifdef means "If Defined", your code essentially tells the preprocessor to check if DEBUG_MSG defined elsewhere. If so, it will include the code you provided.

+4
source

When compiling, try something like this:

 $ gcc -DDEBUG_MSG -o foo foo.c 
+9
source

You would need #define something.

0. In your code.

Directly in the code somewhere before using this flag:

 #define DEBUG_MSG 

1. At the command prompt.

For each source file or respectively in your makefile:

 gcc -DDEBUG_MSG main.c 

(For gcc, the flag is -D<macro-name> , for MSVC it ​​is /D , since ICC is one of the first, depending on your operating system.)

2. In your IDE somewhere.

In the IDE project settings, find where you can set definitions. Under the hood, this is done with 1.

+8
source

The C preprocessor phase will only pass the code inside #ifdef/#endif to the compiler phase if the character is defined.

You can usually do this (at least) in two ways.

First, use the command line switch for the command line, for example:

 gcc -DDEBUG_MSG myprog.c 

( -D means that a preprocessor character should be defined after it, and although this is implementation specific, many compilers use the same switch). The second is to place the line, for example:

 #define DEBUG_MSG 

inside your source code somewhere up to #ifdef .

The first rule is preferable because it allows you to control this behavior without the need to make changes to the source code, so that, for example, you can create a debug and release assembly generated from the same source code.

+2
source

#ifdef will make your macro extended only if DEBUG_MSG defined. You can do this in two ways. Either make #define DEBUG_MSG 1 in your source, or compile with -DDEBUG_MSG (if you use gcc , there are similar flags for other compilers too)

+1
source

All Articles