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

自古美人都是妖i 提交于 2019-12-04 05:26:54

问题


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");

回答1:


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!



回答2:


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

The macros you want to use are __FILE__ and __LINE__ which are the file name and line numbers.



来源:https://stackoverflow.com/questions/23916351/automatically-inserting-filename-line-number-in-logging-statements-of-a-c-prog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!