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

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

问题描述

我在写C程序为嵌入式ARM处理器。我希望看到在日志记录语句源文件名和行号。

由于编译code没有行号和源文件的知识,我寻找各种方法来有这个自动在编译过程中前插入/

有没有我可以使用这个标准的任何工具或编译器功能?

我使用的GCC。

例如:

这是什么我会在源文件中写:

 日志(<##文件名和GT;<#行号#>:Hello World的);

这是什么会真正得到编译:

 日志(foobar.c但是225:Hello World的);


解决方案

通常情况下你会做这样的事情:

  //记录功能
无效日志(为const char *文件,const int的线,为const char * MSG)
{
    fprintf中(标准错误,%S:%D:%S \\ N文件,行,味精);
}//记录宏 - 通过__FILE__ __LINE__和伐木功能
#定义LOG(MSG){做日志(__ FILE__,__LINE__,味精)},而(0)

然后,当你想记录的东西:

  LOG(我们去到这个地步!);

然后将生成日志消息,如:

 的foo.c:42:我们去到了这一点!

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?

I am using GCC.

For example:

This is what I would write in the source file:

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

This is what would actually get compiled:

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

解决方案

Typically you'd do something like this:

// 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!

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

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