LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

How do I create a C macro that displays its calling function's name?

In my code, a function returns a negative number to indicate an error. So instead of saying

error = foo ();
if (error < 0)
{
sprintf (errMsg, "Function foo returned %d", error);
goto Error:
}

...I instead have a macro "negChk" that lets me do this:

negChk (foo(), "foo");

As you can see, I must redundantly pass the function's name to the macro as a string. I'd rather just pass it like this:

negChk (foo());

Here's my macro now, how should I rewrite it to take just one parameter as shown above? ...

#define negChk(fCall, fName)\
\
error = (fCall);\
if (error) {\
testData->result = FAIL;\
sprintf (errMsg, "%s () failed, error code %d", fName, error);\
testData->replaceStr
ingFuncPtr(&testError->errorMessage, errMsg);\
testData->replaceStringFuncPtr (&testData->outBuffer, errMsg);\
if(error < 0) goto Error;\
} else
0 Kudos
Message 1 of 6
(4,730 Views)
CVI includes the macro __FUNCTION__ that shows the function name. I use it exactly for this purpose in addition with the macro __LINE__ that shows the line in the source code where the error arise. Another useful macro is __FILE__ to display the source filename.


Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
0 Kudos
Message 2 of 6
(4,730 Views)
Perfect! 🙂
0 Kudos
Message 3 of 6
(4,730 Views)
Oops, I meant "almost" perfect-- what I'd really like is the function name I'm calling, not the one I'm in.

In the example code above, I would want the string "foo" to show up in my macro message, not the name of whatever function is calling foo.
0 Kudos
Message 4 of 6
(4,730 Views)
Hi,

It may take some changing of your functions, but you can have the functions return an error string that contains the function name and probably some specifics of the error. You could use there the _FILE_ and _FUNCTION_ macros to get the information.

The other option is to assign error codes and have a GetErrorString(,,,) that reads this info from an enum. That is the way that most CVI libraries implement error handling.

Just my 2 cents!

Regards,

Juan Carlos
N.I.
0 Kudos
Message 5 of 6
(4,730 Views)
I'll stick with the _FUNCTION_ macro inside my functions.

I just wish there were a way to get the names of functions that are CVI's (or some other library) into the error message without explicityly typing it.
0 Kudos
Message 6 of 6
(4,730 Views)