Using correct #define preprocessor directive syntax to replace/rename text/function names

48 views Asked by At

What is the correct syntax using the preprocessor directive #define, to replace/rename the following snippet of code from:

printf("\nrxBuffer: %s", rxBuffer);
fprintf(fpOut, "\nReceived Command: %s",rxBuffer);

To:

xil_printf("\nrxBuffer: %s", rxBuffer);
//fprintf(fpOut, "\nReceived Command: %s",rxBuffer);

Not sure how to separate the macro name from the value that will make the proper substitution. To avoid the possibility of substring mis-matching I intended to differentiate the printf from fprintf by including the initial function bracket and quotation mark, but syntactically I wasn't quite shure how to accomplish that?

Example:

#define XIL_VITIS
#ifdef XIL_VITIS
#define printf(" xil_printf("
#define fprintf //fprintf
#endif

Eventually I decided to simply duplicate the files and actually modify the code. But after fooling around with this initially, I was still curious as to what the proper syntax might/would be?

1

There are 1 answers

0
chqrlie On

Here is a solution for your purpose:

#define XIL_VITIS
#ifdef XIL_VITIS
#define printf xil_printf
#define fprintf(...)
#endif

Macros definitions are composed of a macro name, optionally immediately followed by a parenthesized list of argument names and a replacement list, which is a list of C preprocessor tokens.

You cannot use an arbitrary sequence of characters such as printf(" for a macro definition, but if you #define printf as the identifier xil_printf, every occurrence of printf as a C identifier will replaced with xil_printf after the #define line.

Comments in the replacement list will be removed at parse time, not part of the expansion nor inserted as text where the macro is expanded, so #define fprintf //fprintf does not produce the expected effect: fprintf(fpOut, "\nReceived Command: %s",rxBuffer); will expand to (fpOut, "\nReceived Command: %s",rxBuffer); which is a comma expression that will compile to no code unless fpOut or rxbuffer are defined as macros with an expansion that has side effects. You cannot achieve the replacement with a comment exactly, but defining fprintf as a macro with a variable list of arguments and no expansion should achieve the desired effect: disable the fprintf call. The statement will expand to ;, which is not exactly equivalent to commenting the line but more consistent with the program structure.

Be aware that these macros may affect other code where the side effects are not intended and not desirable.