Eamorr
Eamorr

Reputation: 10012

C: `Turn on debug messages

This is probably a really stupid question, but how do I turn on these debug messages in my code?

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

Many thanks in advance,

Upvotes: 5

Views: 3034

Answers (5)

Sebastian Mach
Sebastian Mach

Reputation: 39089

You would have to #define that somehow.

0. In your code.

Directly in your code somewhere before you use that flag:

#define DEBUG_MSG

1. On the command line.

For each sourcefile, or appropriately in your makefile:

gcc -DDEBUG_MSG main.c

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

2. In your IDE, somewhere.

In your IDE's project settings, find where you can put definitions. Under the hood, this is done using 1.

Upvotes: 9

paxdiablo
paxdiablo

Reputation: 881463

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

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

The first is to use a command line switch for the compiler such as:

gcc -DDEBUG_MSG myprog.c

(-D means to define the pre-processor symbol following it and, although this is implementation-specific, many compilers use the same switch). The second is to place a line like:

#define DEBUG_MSG

inside your actual source code somewhere before the #ifdef.

The former is usually preferred since it allows you to control that behaviour without having to make changes to your source code so that, for example, you can have a debug and release build generated from the same source code.

Upvotes: 2

Mihai Maruseac
Mihai Maruseac

Reputation: 21435

#ifdef will make your macro to be expanded only if DEBUG_MSG is defined. You can do this in two ways. Either do a #define DEBUG_MSG 1 in your source or compile using -DDEBUG_MSG (if using gcc, there are similar flags for other compilers too)

Upvotes: 1

user461697
user461697

Reputation:

#ifdef means 'If defined', your code essentially tells the preprocessor to check if DEBUG_MSG is defined somewhere else. If it is, it will include the code you've shown.

Upvotes: 4

Eimantas
Eimantas

Reputation: 49354

When compiling, try something like this:

$ gcc -DDEBUG_MSG -o foo foo.c

Upvotes: 9

Related Questions