Question

I have a task at work to make the static library more secure , in order to do so I need to replace the formatted strings of printf for them to appear differently in the compiled static library , for this to happen it must be done in the pre processor stage .

What I did (and it actually works in visual studio) is the following ( and it is just a pseudo example ):

char * my_array[] = {"abcd", "a %d", " b %d %s "};
#define GENERIC_ARRAY(x) my_array[x]

#define VARIADIC_DEBUG_PRINT(...)   DebugPrintFunction (__FILE__, __LINE__, __func__, __VA_ARGS__)
#define PRINT_BY_LEVEL(x)           VARIADIC_DEBUG_PRINT x
#define REPLACE_STRING(x,...)       PRINT_BY_LEVEL((GENERAL_LEVEL,GENERIC_ARRAY(__COUNTER__),__VA_ARGS__))

#define MY_PRINTF(x,...)      REPLACE_STRING((void*)0,(void*)0,__VA_ARGS__)

All of this overhead is for me to trick the compiler to accept prints without any arguments except the string

So when testing it in my main.c I tried the following And it worked :

MY_PRINTF("Hello World");
MY_PRINTF("My Val %d", i);
MY_PRINTF("MY VAL %d My String %s", i, s);

But when switching to GCC, he does not like the format of the first print i.e :

MY_PRINTF("Hello World");

And throws me an compilation error :

error: expected expression before ')' token

Any ideas how may I trick the compiler and accept it ? or maybe better ideas how to rename the string safely after compilation ?

Was it helpful?

Solution

You can try something like :

#include <stdio.h>
#define PRINT(x, ...) printf(x, ##__VA_ARGS__)

int main (int argc, char *argv[]) {
    PRINT("Hello\n");
    PRINT("World %d\n", 42);
    return 0;
}

It works with gcc 4.8 (not tried with earlier version, but it should work too)

OTHER TIPS

Using ##__VA_ARGS__, you may try:

#define MY_PRINTF(x, ...) \ 
    VARIADIC_DEBUG_PRINT(GENERAL_LEVEL, GENERIC_ARRAY(__COUNTER__), (void*)0, (void*)0, ##__VA_ARGS__)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top