1

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 ?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Fluffy
  • 337
  • 1
  • 5
  • 16

2 Answers2

4

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)

NiBZ
  • 532
  • 2
  • 11
  • But i need to insert my new string instead of the old string , and it does not happen in your example ... – Fluffy Jan 20 '14 at 13:53
  • 1
    The idea is to use `##__VA_ARGS__` instead of `__VA_ARGS__` on you macros. When `__VA_ARGS__` is empty, this avoids including the trailing comma. In this case, the `PRINT("Hello\n")` is expanded to `printf("Hello\n")` and not `printf("Hello\n",)` which would cause the **error: expected expression before ')' token** gcc error. – NiBZ Jan 20 '14 at 13:56
  • See why the ``##_VA_ARGS__`` hack works: https://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html –  Sep 15 '16 at 11:28
1

Using ##__VA_ARGS__, you may try:

#define MY_PRINTF(x, ...) \ 
    VARIADIC_DEBUG_PRINT(GENERAL_LEVEL, GENERIC_ARRAY(__COUNTER__), (void*)0, (void*)0, ##__VA_ARGS__)
Jarod42
  • 203,559
  • 14
  • 181
  • 302