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

标签 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;
}

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

示例代码打印“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)

2.

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

关于c++ - 如何获取另一个函数的 __LINE__ 值(在调用该函数之前)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47319886/

相关文章:

c++ - 将字符数组的内容复制到 Qt 中的 QString

android - 如何在Linux操作系统中使用arm-linux-androideabi-gcc编译器构建libargp库

c结构问题

java - JNI 无法加载 native 库

c++ - 如何将 LibVLC 中的 D3DDevice 传递为 "HWND"

c++ - 我如何简单地读取控制台输出

c++ - 我想通过OpenGL创建3D金字塔

c - 如何在没有嵌套循环的情况下实现三项式展开。

c - 使用数组打印菜单图标不起作用?

c++ - 判断两个矩形是否相交