简体   繁体   中英

How to define DEBUG macro in C

I have a DEBUG macro in my C code but if I want to define it how would I do this from the compiler? I am using the gcc compiler with the following switches:

gcc -ansi -W -Wall -pedantic project.c 

I know that the -D switch is used to define macros but im not sure where to place it. I am not sure if this is how to define it, It doesnt display anything when I run my code

./a -DDEBUG 

Thanks

Please read this ... http://tigcc.ticalc.org/doc/comopts.html

It suggests the following ...

-D name

    Predefine name as a macro, with definition 1. 

when you use the following ..

gcc -ansi -W -Wall -pedantic -DDEBUG project.c

this defines DEBUG to be '1' ... you can then use the following in code ...

#ifdef DEBUG

<debug code added here>

#endif

Final thoughts, I would suggest renaming your define to something a little less generic.

You use the -D switch when compiling the code:

gcc -ansi -W -Wall -pedantic -DDEBUG project.c 

This

./a -DDEBUG 

doesn't define DEBUG . It passes -DDEBUG as an argument to your main() function.

I suppose here

./a 

you are running the executable obtained from your C code. There is no sense to call the executable with a debug macrodefinition option like -DDEBUG. This kind of debug macrodefinition is used at compile time to choose what parts of your code to activate or deactivate, and not at build time (object linkage time) nor at runtime.

Macrodefinitions of all kinds are used before compile time. After the code is compile into object files, macros are already processed. They are either substituted by there definitions or processed:

#define A 10
#define SUM(x, y) ((x)+(y))
#define DBG 1
#if defined(DBG)
    // do some debug operations (printfs, etc.)
#endif 
int a = A; // a = 10;
int b = A+1; // b = 11;
int c = SUM(a, b); // c = ((a)+(b));

If DBG is defined (either in the source code as #define DBG or #define DBG 1) the debug operations C code is activated and compiled into the object file. If DBG is not defined then the debug operations C code is removed from the created object file.

This is why there is no sense to try passing a debug macro to an executable. Calling ./a -DDEBUG will result in -DDEBUG be passed as argument to the executable and can be read in the main() function as follows:

int main(int argc, char **argv)
{
    int i;
    printf("%d %s", argc, argv[0]);
    for(i=0; i<argc; i++)
        printf("%s", argv[i]); // first argument is always the name of the execute program
    return 0;
}

To answer your question: I am not an expert with gcc, but I suppose you should pass -DDEBUG to gcc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM