对于当前存在的测试框架,我需要(在第一个调用期间)将该函数内部片段的行号传递给该函数。像这样:
#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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句