开发者

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,


When compiling, try something like this:

$ gcc -DDEBUG_MSG -o foo foo.c


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.


#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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜