Automatically inserting filename & line number in

2019-03-02 05:25发布

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

2条回答
SAY GOODBYE
2楼-- · 2019-03-02 05:37

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.

查看更多
老娘就宠你
3楼-- · 2019-03-02 05:40

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!
查看更多
登录 后发表回答