Is there a way to get the line number with out a macro in c++?

前端 未结 2 490
说谎
说谎 2021-01-28 05:16

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_

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-28 06:04

    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?

    Not in general.

    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)

提交回复
热议问题