自动插入文件名 &C 程序的日志记录语句中的行号 [英] Automatically inserting filename & line number in logging statements of a C program

查看:20
本文介绍了自动插入文件名 &C 程序的日志记录语句中的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C 为嵌入式 ARM 处理器编写程序.我想在日志记录语句中看到源文件名和行号.

I am writing a program for an embedded ARM processor in C. I would like to see the source filename and line number in the logging statements.

由于编译后的代码不知道行号和源文件,我正在寻找在编译过程之前/期间自动插入它的方法.

As the compiled code has no knowledge of line numbers and source files, I am looking for ways to have this inserted automatically before / during the compile process.

是否有任何标准工具或编译器功能可以用于此目的?

Are there any standard tools or compiler features that I can use for this?

我正在使用 GCC.

例如:

这是我在源文件中写的:

This is what I would write in the source file:

log("<#filename#> <#linenumber#> : Hello World");

这是实际编译的内容:

log("Foobar.c 225 : Hello World");

推荐答案

通常你会这样做:

// logging function
void log(const char * file, const int line, const char *msg)
{
    fprintf(stderr, "%s:%d: %s\n", file, line, msg);
}

// logging macro - passes __FILE__ and __LINE__ to logging function
#define LOG(msg) do { log(__FILE__, __LINE__, msg) } while (0)

然后当你想记录一些东西时:

Then when you want to log something:

LOG("We made it to this point!");

然后会生成一条日志消息,例如:

which will then generate a log message such as:

foo.c:42: We made it to this point!

这篇关于自动插入文件名 &amp;C 程序的日志记录语句中的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆