簡體   English   中英

如何獲取另一個函數的__LINE__值(在調用該函數之前)?

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

對於當前存在的測試框架,我需要( 在第一次調用期間 )向該函數傳遞該函數內部片段的行號。 像這樣的東西:

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

在@rici的回答和評論之后 ,最接近我需要的是以下內容:

#include <stdio.h>

#define LINE_NUM_TESTER() \
    enum { LINE_NUM = __LINE__ }; \
    \
    void line_num_tester(int line_num) \
    { \
      if(line_num == __LINE__) \
        printf("OK\n"); \
      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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM