Is it safe to disable buffering with stdout and stderr?

前端 未结 5 463
我寻月下人不归
我寻月下人不归 2021-02-03 11:01

Sometimes we put some debug prints in our code this way

printf(\"successfully reached at debug-point 1\\n\"); 

some code is here

printf(\"successfully reached          


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-02-03 11:19

    A possible way might be to have a bool dodebug global flag and define a macro like e.g.

    #ifdef NDEBUG
    #define debugprintf(Fmt,...) do{} while(0)
    #else
    #define debugprintf(Fmt,...) do {if (dodebug) {                 \
       printf("%s:%d " Fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__); \
       fflush(stdout); }} while(0)
    #endif
    

    Then inside your code, have some

    debugprintf("here i=%d", i);
    

    Of course, you could, in the macro above, do fprintf instead... Notice the fflush and the appended newline to the format.

    Disabling buffering should probably be avoided for performance reasons.

提交回复
热议问题