如何获取另一个函数的__LINE__值(在调用该函数之前)?

Rob*_*min 6 c c++

对于目前已有的测试框架我需要通过(第一最呼叫期间)的功能片段的行号函数的内部.像这样的东西:

#include <stdio.h>
void func(int line_num)
{
#define LINE_NUM  (__LINE__ + 1)
  if(line_num == __LINE__) // Check the passed arg against the current line.
    printf("OK");
  else
    printf("FAIL");
}

int main(void)
{
  func(LINE_NUM); // Pass to the func the line number inside of that func.
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

(这是更复杂功能的简约版本).

因为示例代码打印"FAIL".

如果我传递绝对值5,例如func(5)然后它打印"OK".我不喜欢绝对值,5因为如果我在func定义前添加一行,那么绝对值将需要更正.

而不是#define LINE_NUM (__LINE__ + 1)我也尝试了以下内容:

1.

#define VALUE_OF(x) x
#define LINE_NUM    (VALUE_OF(__LINE__) + 1)
Run Code Online (Sandbox Code Playgroud)

2.

#define VAL(a,x)    a##x
#define LOG_LINE()    ( VAL( /*Nothing*/,__LINE__) + 1)
Run Code Online (Sandbox Code Playgroud)

3.

#define VALUE_OF2(x) x
#define VALUE_OF(x)     VALUE_OF2(x)
#define LINE_NUM  (VALUE_OF(__LINE__) + 1)
Run Code Online (Sandbox Code Playgroud)

我正在使用:

gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Run Code Online (Sandbox Code Playgroud)

在我的示例代码中,func()获得的值是14(呼叫站点行号+ 1).

ric*_*ici 5

您无法让预处理器__LINE__在宏定义中进行扩展.这不是预处理器的工作方式.

但是你可以创建全局常量.

#include <stdio.h>

static const int func_line_num = __LINE__ + 3;
void func(int line_num)
{
  if(line_num == __LINE__) // Check the passed arg against the current line.
    printf("OK");
  else
    printf("FAIL");
}

int main(void)
{
  func(func_line_num); // Pass to the func the line number inside of that func.
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢static const int,无论出于何种原因,您可以使用枚举:

enum { FUNC_LINE_NUM = __LINE__ + 3 };
Run Code Online (Sandbox Code Playgroud)

不幸的是,无论你使用一个全局常量或枚举,你必须把在文件范围的定义,这可能使有些从使用点遥远.但是,为什么需要使用测试的精确行号,而不是(例如)函数的第一行甚至任何保证唯一的整数,并不是很明显:

#include <stdio.h>

// As long as all uses of __LINE__ are on different lines, the
// resulting values will be different, at least within this file.
enum { FUNC_LINE_NUM = __LINE__ };

void func(int line_num)
{
  if(line_num == FILE_LINE_NUM) // Check the passed arg against the appropriate constant.
    printf("OK");
  else
    printf("FAIL");
}

int main(void)
{
  func(func_line_num); // Pass to the func the line number inside of that func.
  return 0;
}
Run Code Online (Sandbox Code Playgroud)