英文:
C++: Create a (sort of) "decorator" to self document / self print debug info about code
问题
我已为调试目的创建了以下工作流程。
我定义了一个全局宏
#define PRINT_CALL(x) std::cout << "(CALL) " << x << std::endl
以在调用时通知。在我的用例中,它被如下使用:
void foo() {
PRINT_CALL("foo()");
// 做一些事情
}
这使得在我的用例中调试变得更容易。有没有一种自动化这个过程的方法?以下是我想到的 绝对非法 的 C++ 语法:
#define_decorator call_me(x) std::cout << "(CALL) " << x << std::endl
@call_me
void foo() {
// 做一些事情
}
// ==> 产生与上述完全相同的结果。
我希望你能理解我的意思。正如我所说,语法显然是糟糕的;因为我不知道有这样的功能,也没有在网上找到有用的信息,也许有人知道一个技巧。感谢所有的回答!
英文:
I have for debugging purposes created following workflow.
I defined a global macro
#define PRINT_CALL(x) std::cout << "(CALL) " << x << std::endl
to notify whenever something is called. Trivially it is used like so:
void foo() {
PRINT_CALL("foo()");
// do stuff
}
This makes debugging much easier in my use case. Is there a way to automate this? Here is what I had in mind in totally illegal C++ syntax:
#define_decorator call_me(x) std::cout << "(CALL) " << x << std::endl
@call_me
void foo() {
// do stuff
}
// ==> resulting in the exact same outcome as above.
I hope you get the idea. As I said, syntax is obviously trash; since I don't know of such a functionality and didn't find any useful information online, maybe someone knows a hack. Appreciate all answers!
答案1
得分: 0
如果你真的想在你的代码中添加调试注释,你可以根据你的编译器和语言标准使用__FUNCTION__
、__func__
、__PRETTY_FUNCTION__
等中的任何一个。例如,定义宏如下所示:
#define PRINT_CALL() std::cout << "(CALL) " << __func__ << std::endl
然后像这样使用它:
void foo() {
PRINT_CALL(); // 无需重新编写名称 'foo'
// 做一些事情
}
了解更多信息,请参阅这里:
https://stackoverflow.com/questions/4384765/whats-the-difference-between-pretty-function-function-func
不过,我强烈建议不这样做,考虑使用调试器和断点。
英文:
Assuming you really want to litter your code with debug annotations like this, you could use any of __FUNCTION__
, __func__
, __PRETTY_FUNCTION__
etc., depending on your compiler and the language standard you are using.
I.e. define the macro like this
#define PRINT_CALL() std::cout << "(CALL) " << __func__ << std::endl
and use it like so
void foo() {
PRINT_CALL(); // No need to rewrite the name 'foo'
// do stuff
}
See here for more:
https://stackoverflow.com/questions/4384765/whats-the-difference-between-pretty-function-function-func
However I would strongly advise against this and consider using a debugger and breakpoints.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论