如何使用预处理器在编译时计算和存储哈希值?
我有一个本机 C++ 程序,它使用“事件队列”在不同线程上执行函数。 我在堆上分配一个“事件”类,并将其放入我的线程队列之一中以供执行。
一切都很好,但很难追溯到这些“事件”的起源。 我希望每个“事件”都存储一些有关其来源的信息。 现在我使用内部 _ReturnAddress()
来实现此目的,但我还希望获得文件名字符串和行号。 我很喜欢使用宏来安排我的“事件”。
当然,我不想为拥有这些字符串而付出代价。
有没有什么方法可以让预处理器构建并转储到文件映射 “id” => “文件,行”,其中“id”将是每次宏扩展时递增的某个唯一数字? 我可以将该 ID 存储为我的来源。
或者也许计算一个非常短的文件名哈希,以便我可以在运行时使用它?
欢迎任何想法。
I have a native C++ program that uses "event queues" to execute functions on different threads. I allocate an "event" class on the heap, and put it on one of my threads' queues for execution.
It all works great, but it's very difficult to trace back the origin of these "events". I would like each "event" to store some information pertaining to where it came from. Right now I use intrinsic _ReturnAddress()
for that, but I would also like to have the file name string and line number. I'm fine with using macros to schedule my "events".
Of course I don't want to pay the price for having these strings.
Is there any way of having the preprocessor build up and dump to file a map of
"id" => "file,line", where the "id" would be some unique number incremented each time my macro gets expanded? I could store that id as my origin.
Or maybe compute a very short hash of the file name so I could use that at run time?
Any ideas are welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于 ID,您可以使用
__COUNTER__。
来自 http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx:
__FILE__
和__LINE__
可用于跟踪事件的分配位置。但为什么要追溯这些事件的源头呢? 如果这是出于调试目的,您可能需要考虑在特殊的调试模式下将使用 StackWalk64 收集的堆栈跟踪嵌入到您的类中 - 它会给您提供比原点更多的有用信息。
For ID you could use
__COUNTER__.
From http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx:
__FILE__
and__LINE__
can be used to track where the event was allocated.But why do you want to track back the origin of these events? If this is for debugging purposes, you might want to look into embedding a stack trace, collected using StackWalk64, into your class when in a special debug mode - it'll give you a lot more useful information than just place of origin.
编写您自己的预处理器。
不必那么难,只需解析 .cpp 文件并搜索您自己定义的一些语法即可。 找到它后,将文件名和行(预处理器必须计算新行数)添加到某个日志文件中。 不过,它必须将您自己的宏扩展为 C++。 将所有内容写入临时文件,然后将其传递给“真正的”编译器。
干杯!
Write your own preprocessor.
Doesn't have to be that hard, just parses through the .cpp file and searches for some syntax that you have defined yourself. When finding it, append file name and line (the preprocessor would have to count number of new lines) to some log file. It would have to expand your own macro into c++ though. Write everything to a temporary file, which you in turn pass on to the "real" compiler.
Cheers !
查看 Boost.Preprocessor。 它是一组仅包含头文件的宏,用于使用标准 C 预处理器执行强大的操作。
它非常复杂(我不声称理解它),但我认为它可以做你想做的事。 文档此处和此处。
Check out Boost.Preprocessor. It's a header-only set of macros for doing powerful stuff with the standard C preprocessor.
It's pretty complicated (I make no claim to understand it) but I think it can do what you want. Docs here and here.