2011年6月17日 星期五

useful message when debuging c program on linux

__FILE__ , __LINE__ , __FUNCTION__
在log mesage時加入此類參數,可以有效得知到底目前程式跑到哪邊!
例:
#include "global.h"
int main(int argc, char **argv)
{
    printf("%s(%d)-%s: this is main\n",__FILE__,__LINE__,__FUNCTION__);
    funca();
    printf("%s(%d)-%s: this is main\n",__FILE__,__LINE__,__FUNCTION__);
    funcb();
    printf("%s(%d)-%s: this is main\n",__FILE__,__LINE__,__FUNCTION__);
    return 0;
}
root@xuanfei-desktop:~/cpropram/2# gcc -Wall funca.c funcb.c main.c
root@xuanfei-desktop:~/cpropram/2# ./a.out
main.c(4)-main: this is main
this is function
main.c(6)-main: this is main
this is function
main.c(8)-main: this is main

我們亦可利用#define事先宣告
#ifndef CLOBAL_H
        #define GLOBAL_H
        #include <stdio.h>
        int funca(void);
        int funcb(void);
        #define DEBUGFMT  "%s(%d)-%s"
        #define DEBUGARGS __FILE__,__LINE__,__FUNCTION__
#endif
root@xuanfei-desktop:~/cpropram/2# cat funca.c
#include "global.h"
int funca(void)
{
printf (DEBUGFMT " this is function\n",DEBUGARGS);
return 0;
}
root@xuanfei-desktop:~/cpropram/2# cat funcb.c
#include "global.h"
int funcb(void)
{
printf (DEBUGFMT " this is function\n",DEBUGARGS);
return 0;
}
root@xuanfei-desktop:~/cpropram/2# cat main.c
#include "global.h"
int main(int argc, char **argv)
{
    printf(DEBUGFMT "this is main\n", DEBUGARGS);
    funca();
    printf(DEBUGFMT "this is main\n", DEBUGARGS);
    funcb();
    printf(DEBUGFMT "this is main\n", DEBUGARGS);
    return 0;
}
root@xuanfei-desktop:~/cpropram/2# gcc -Wall funca.c funcb.c main.c
root@xuanfei-desktop:~/cpropram/2# ./a.out
main.c(4)-mainthis is main
funca.c(4)-funca this is function
main.c(6)-mainthis is main
funcb.c(4)-funcb this is function
main.c(8)-mainthis is main
======================================

沒有留言:

張貼留言