How to Write macro debug macro with Variable Parameter count

Source: Internet
Author: User

Compiler built-in macros:

First, we will introduce several built-in macro definitions of the compiler. These macro definitions can not only help us write cross-platform source code, but also help us output useful debugging information flexibly.

The ansi c standard has several predefined macros (which are also commonly used ):

_ Line __: Insert the current source code line number into the source code;

_ File __: insert the name of the current source file into the source file;

_ Date __: Insert the current compilation date into the source file

_ Time __: Insert the current compilation time into the source file;

_ Stdc __: when the program strictly follows the ansi c standard, the ID is assigned 1;

_ Cplusplus: This identifier is defined when a C ++ program is compiled.

 

Debug (format ,...) printf ("file:" _ file _ ", line: % d:" format "/N", _ line __,#__ va_args __)

That's it! Below, all the debug information will be output in this way:

File: XXX, line: XXX ,.......

Finally:

Finally, the old rule is coding testing.

 

View plain · 10 · 20 · 30 · 40 · ····· · 90 ··· · 140 · 150
  1. // ================================================ ==============================================
  2. // Name: Debug. cpp
  3. // Author: Boyce
  4. // Version 1.0
  5. // Copyright: PKU
  6. // Description: Hello world in C ++, ANSI-style
  7. // ================================================ ==============================================
  8. # Include
  9. # DEFINE _ debug __
  10. # Ifdef _ debug __
  11. # Define debug (format ,...) printf ("file:" _ file _ ", line: % 05d:" format "/N", _ line __, ##__ va_args __)
  12. # Else
  13. # Define debug (format ,...)
  14. # Endif
  15. Int main (){
  16. Char STR [] = "Hello World ";
  17. Debug ("A ha, check me: % s", STR );
  18. Return 0;
  19. }

 

 

Test results:

 

The c99 compiler standard has finally changed this situation. It allows you to define variadic macros so that you can use macros with Variable Parameter tables. Variable Parameter macros look like the following:

# Define debug (...) Printf (_ va_args __)

The default number indicates a variable parameter table. Use the reserved name_va_args _ to pass the parameter to the macro. When macro calls are expanded, the actual parameters are passedPrintf (). For example:

Debug ("y = % d/N", y );

The processor will replace macro calls:

Printf ("y = % d/N", y );

BecauseDebug ()Is a variable parameter macro, you can pass different numbers of parameters in each call:

Debug ("test"); // A PARAMETER

Variable Parameter macros are not officially supported by ANSI/iso c ++. Therefore, you should check your compiler to see if it supports this technology.

 

 

You can use variable parameter macros of GCC and c99 to conveniently print debugging information.


The Variable Parameter macro definition provided by GCC preprocessing is really useful:

#ifdef DEBUG
#define dbgprint(format,args...) /
fprintf(stderr, format, ##args)
#else
#define dbgprint(format,args...)
#endif

After this definition, dbuplint can be used in the Code, for example, dbuplint ("AAA % s", _ file __);. I think this function is cool: em11:

Below is the c99 method:

#define dgbmsg(fmt,...) /
             printf(fmt,__VA_ARGS__)

 

 

The new c99 specification supports macros with variable parameters.

The specific usage is as follows:

The following is the program code:

# Include <stdarg. h> # include <stdio. h>

# Define logstrings (FM,...) printf (FM ,__ va_args __)

Int main () {logstrings ("Hello, % d", 10); Return 0 ;}

But now it seems that only GCC is supported.

 

'##' In the macro of variable parameters


Macro with variable parameters (macros with a variable number of arguments)

In Iso c 1999, macros can be defined with variable parameters like functions. Macro syntax is similar to function syntax. The following is an example:

# Define debug (format,...) fprintf (stderr, format, _ va_args __)

Here ,'... 'Indicates a variable parameter. When this type of macro is called, it (here '... ') Is expressed as zero or multiple symbols, including commas (,) until the end of the right arc. When called, in macro body, the symbolic sequence set replaces the _ va_args _ identifier. For more information, see the CPP manual.

GCC always supports complex macros. It uses a different syntax so that you can give variable parameters a name, just like other parameters. For example:

# Define debug (format, argS...) fprintf (stderr, format, argS)

This is exactly the same as the macro example defined in iso c above, but it is more readable and easy to describe.

Gnu cpp has two more complex macro extensions that support the preceding two formats.

In standard C, you cannot omit variable parameters, but you can pass it an empty parameter. For example, the following macro call is invalid in iso c because the string is not followed by a comma:

Debug ("A message ")

In this case, gnu cpp allows you to ignore variable parameters completely. In the above example, the compiler still has a problem (complain), because after the macro is expanded, there will be an extra comma behind the strings.

To solve this problem, CPP uses a special '#' operation. The writing format is:

# Define debug (format,...) fprintf (stderr, format, ##_ va_args __)

Here, if the variable parameter is ignored or empty, the '#' operation will remove the comma before the Preprocessor. If you provide some variable parameters during macro calls, gnu cpp will also work normally, and it will put these variable parameters behind the comma. Like other pasted macro parameters, these parameters are not macro extensions.





How to Write macro with variable number of parameters


A popular technique is to define and call a macro using a single ''parameter enclosed by arc. When a macro is extended, the parameter becomes like printf () the entire parameter list of such a function.

    #define DEBUG(args) (printf("DEBUG: "), printf args)

if(n != 0) DEBUG(("n is %d/n", n));

The obvious defect is that the caller must remember to use an additional arc.

GCC has an extension that allows function macros to accept variable number parameters. But this is not a standard. Another possible solution is to use multiple macros (debug1, debug2, etc.) based on the number of parameters, or use commas to play such a trick:

    #define DEBUG(args) (printf("DEBUG: "), printf(args))
#define _ ,

DEBUG("i = %d" _ i);

C99 introduces the formal support for function macros with variable numbers of parameters. Add the symbol at the end of the macro ''prototype... (like in the Variable Parameter Function Definition), the pseudo macro _ va_args _ in the macro definition will be replaced with the variable parameter in the call.

Finally, you can always use real functions to accept clearly defined variable parameters.

If you need to replace the macro, use a function and a non-FUNCTION macro, such as # define printf myprintf.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.