Duanxx C + + Learning: Debugging code with __FILE__,__LINE__,__VA_ARGS__

Source: Internet
Author: User

__file__,__line__

When we debug C + + code, what we want to know is, of course, the first line of the file that the program is currently on, and there are two macros: __file__ and __line__, which returns the path to the current file, and the current line.

Here the test code is as follows:

#include <cstdio>int main () {  printf ("%s:%d", __file__,__line__);  printf ("\ n");  return 0;}


The results under Windows Run as:






The results of the Linux system operation are as follows:




As you can see, under Windows, __FILE__ returns the Full path , and with g++ compiled under Linux, the return is only file name .







__va_args__

This is a variable parameter macro that was supported from C99, which previously supported only variable parameters of a function in the C language.


For example, our most common printf function:

void printf (const char* format, ...);

Here's the ellipsis ..., yes . variable Parameters .

The __VA_ARGS__ macro is the variable parameter that implements the macro:

#define DEBUG (...) printf (__va_args__)

The test code is as follows:

#include <cstdio> #define DEBUG (...) printf (__va_args__) int main () {  debug ("Duanxx%d\n", 123);  return 0;}

Running results under Windows:



Running results under Linux:








A single line of debug macros

With the instructions above, you can write the following debug macro:

#define DEBUG (FMT, ...)   fprintf (stdout, "%s:%d duanxx Debug   " FMT "\ n", __file__, __line__, # #__VA_ARGS__)



Test code:

#include <cstdio> #define DEBUG (FMT, ...)   fprintf (stdout, "%s:%d duanxx debug   " FMT "\ n", __file__, __line__, # #__VA_ARGS__) int main () {  debug ("Duanxx%d\n ", 123);  return 0;}




Results under Windows:





Results under Linux:




Duanxx C + + Learning: Debugging code with __FILE__,__LINE__,__VA_ARGS__

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.