I am writing a logger and I would like the logger to also record which line, function, and file called it. I have tried #define my_logger(format, ...) _log(format, __LINE_
Is there a way where I can declare a normal function like void my_logger(const char* format, ...) and in the function definition have it know the line it was called from with something equivalent to
__LINE_FUNCTION_WAS_CALLED_FROM__
if such macro existed?
On Linux x86-64, in 2020, with all your (or other) C++ code (C++11 or better) compiled with DWARF debug information (so if using a recent GCC, with g++ -g -Wall
and if using a recent Clang, with clang++ -g -Wall
), you might use Ian Taylor's libbacktrace library.
Also, a good optimizing compiler is allowed to inline expand or unroll loop (and actually g++ -O2
or clang++ -O2
will do both, and so does Microsoft compilers), and then your __LINE_FUNCTION_WAS_CALLED_FROM__
makes no sense.
As an open source example, RefPerSys is using it to show backtrace and part of call stacks. Disclaimer: RefPerSys is my own project.
Be aware of ASLR related to shared libraries. And plugins loaded with dlopen(3) add complexity to the picture.
At a minimum it needs to work on GCC and really should be cross-platform.
It cannot be cross-platform. Some architectures (e.g. IBM Z series) have different calling conventions, and you'll need efforts (or pay them) to port libbacktrace
to them.
You might consider debugging on some systems, then porting your code to others, and you should consider using frameworks like libSFML or Qt for your game engine. My opinion is to recommend debugging your code on Linux (to make it correct) and later porting it to Windows.
If you need cross-compilation, things become harder. you may also consider metaprogramming approaches: writing your C++ code generator or using other ones (e.g. like SWIG or ANTLR)