如何获取另一个函数的值__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;
}
(这是更复杂功能的简约版本(。
示例代码打印"失败"。
如果我传递一个绝对值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;
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- cv::line函数是画倒置的线条
- source.cpp:LINE:COL: error:这里不允许定义函数
- c++中的is_open()函数总是返回0值,而getLine(myFile, line)不返回任何值
- c++对各种函数的未定义引用,如line(),initgraph()