获取被调用函数C的行号

时间:2012-08-19 23:01:37

标签: c line-numbers

有没有办法获得一个函数在C中被调用而没有像下面这样做? 定义可以使一段时间后变得乏味,不得不使用DP而不是{像往常一样,难以阅读;但是添加 LINE 作为每个函数的第一个参数只是我不愿意做的事情。

    #include <stdio.h>
    #include <stdlib.h>
    #include <stdarg.h>
    #define println(x,...) printf(x,##__VA_ARGS__);printf("\n");
    /*
     *I would like to be able to replace __LINE__ with the line
     *each function was called on, or replace my DP define completely...
    */
    #ifdef _DEBUG_
        #define DP { println("%s:%d\t%s()",__FILE__,__LINE__,__FUNCTION__);
    #else
        #define DP {
    #endif
    void calledFunc()
    DP
        println("something something something");
    }
    void cFunc(int line)
    {
        println("%s:%d\t%s()",__FILE__,line,__FUNCTION__);
    }
    int main()
    DP
        calledFunc();
        /* ...and I don't want to have to do this all the time either*/
        cFunc(__LINE__);
    }

1 个答案:

答案 0 :(得分:1)

可以替代打印行文件名/编号。它被称为“LocationID”或LID。

LID是项目范围计数器生成的数字。计数器的最新值应存储在源文件中,并像任何其他源文件一样检入/检出源控制系统。计数器的值可以加扰。这迫使其正确使用。你使用它像:

   #ifdef _DEBUG_
        #define DP(x, msg) println("%d: %s", x, msg);
   #endif

并在您的来源:

DP (3517, "Here we are.")

LID的优点是:

  1. 它们对于修改源文件是稳定的,包括重命名文件/函数。
  2. 很容易在消息来源中找到它们。
  3. 日志文件比文件名和函数名称更紧凑,更清晰。
  4. 我多次使用它并证明它是好的。在开发人员之间生成和分配LID值是一种开销,但结果是这项工作的价格的10倍。

相关问题