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

How to get a value of __LINE__ of another function (before calling that function)?

本文关键字:函数 LINE 调用 何获取 获取 另一个      更新时间:2023-10-16

对于当前存在的测试框架,我需要(在第一次调用期间(向函数传递该函数内部片段的行号。像这样:

#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;
}

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

示例代码打印"失败"。

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

除了#define LINE_NUM (__LINE__ + 1)我还尝试了以下方法:

1.

#define VALUE_OF(x) x
#define LINE_NUM    (VALUE_OF(__LINE__) + 1)

阿拉伯数字。

#define VAL(a,x)    a##x
#define LOG_LINE()    ( VAL( /*Nothing*/,__LINE__) + 1)

3.

#define VALUE_OF2(x) x
#define VALUE_OF(x)     VALUE_OF2(x)
#define LINE_NUM  (VALUE_OF(__LINE__) + 1)

我正在使用:

gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

在我的示例代码中,func()获取的值为 14(呼叫站点行号 + 1(。

您无法让预处理器在宏定义中展开__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;
}

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

enum { FUNC_LINE_NUM = __LINE__ + 3 };

不幸的是,无论您使用全局常量还是枚举,都必须将定义放在文件范围内,这可能会使其与使用点有些距离。但是,为什么需要使用测试的精确行号,而不是(例如(函数的第一行,甚至任何保证是唯一的整数,都不是很明显的:

#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;
}

在@rici的出色回答和评论之后,最接近我需要的是以下内容:

#include <stdio.h>
#define LINE_NUM_TESTER() 
    enum { LINE_NUM = __LINE__ }; 
    
    void line_num_tester(int line_num) 
    { 
      if(line_num == __LINE__) 
        printf("OKn"); 
      else 
        printf("FAIL. line_num: %d, __LINE__: %d.n", line_num, __LINE__); 
    }
LINE_NUM_TESTER()
int main(void)
{
  line_num_tester(LINE_NUM);
  return 0;
}