views:

173

answers:

3

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.

+4  A: 

For ID you could use __COUNTER__.

From http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx:

Expands to an integer starting with 0 and incrementing by 1 every time it is used in a compiland.

__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.

Michael
Interesting idea. I will have to look into StackWalk64 some more.The reason I want the origin is for tracing purposes in case the app crashes. It pretty much always fails within the message loop, so I have no clue where the message came from. I have some tracing for debug builds, but would also like something for production.
Filip
I'd definitely look into StackWalk64 then. You might run into issues if you generate very large numbers of events in a short period (like tens of thousands a second or more), then the cost of StackWalk might be prohibitive to be on all the time.
Michael
+2  A: 

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 !

Magnus Skog
+1  A: 

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.

jwfearn