简体   繁体   English

在C程序的日志记录语句中自动插入文件名和行号

[英]Automatically inserting filename & line number in logging statements of a C program

I am writing a program for an embedded ARM processor in C . 我正在用C编写用于嵌入式ARM处理器的程序。 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. 我正在使用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!

There is a standard set of predefined macros as part of the preprocessor: https://gcc.gnu.org/onlinedocs/gcc-4.9.0/cpp/Standard-Predefined-Macros.html 作为预处理器的一部分,有一组标准的预定义宏: https : //gcc.gnu.org/onlinedocs/gcc-4.9.0/cpp/Standard-Predefined-Macros.html

The macros you want to use are __FILE__ and __LINE__ which are the file name and line numbers. 您要使用的宏是__FILE____LINE__ ,它们是文件名和行号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM