1

This is quite similar to GCC define function-like macros using -D argument but I couldn't find a relation to my use case.

Consider the following code, main.c:

#include <stdio.h>

const char greeting[] = "hello world";

//#define printf(fmt, ...) (0)

int main() {
    printf("%s!\n", greeting);
    return 0;
}

If I compile and run this, it works as expected:

$ gcc -Wall -g main.c -o main.exe
$ ./main.exe
hello world!
$

Ok, now I want to How to disable printf function? so I uncomment the #define in the code; I get some warnings, but things again work as as expected (as there is no printout):

$ gcc -Wall -g main.c -o main.exe
main.c: In function 'main':
main.c:5:26: warning: statement with no effect [-Wunused-value]
    5 | #define printf(fmt, ...) (0)
      |                          ^
main.c:8:5: note: in expansion of macro 'printf'
    8 |     printf("%s!\n", greeting);
      |     ^~~~~~
$ ./main.exe
$

Now, go back to the example as originally posted - that is, comment the #define like - and let's try to set that define via the command-line -D argument:

$ gcc -Wall -D'printf(fmt, ...)=(0)' -g main.c -o main.exe
<command-line>: error: expected identifier or '(' before numeric constant
main.c: In function 'main':
<command-line>: warning: statement with no effect [-Wunused-value]
main.c:8:5: note: in expansion of macro 'printf'
    8 |     printf("%s!\n", greeting);
      |     ^~~~~~

Well, the command line argument -D'printf(fmt, ...)=(0)' causes the compilation to fail.

Is there any way I can format this macro somehow, so I can set it via the gcc command line using the -D argument? (Bonus: can it be formulated somehow, so it does not raise warnings like "statement with no effect")


EDIT: contents of C:/msys64/mingw64/include/stdio.h lines 366 to 372:

    366 __mingw_ovr
    367 __attribute__((__format__ (gnu_printf, 1, 2))) __MINGW_ATTRIB_NONNULL(1)
    368 int printf (const char *__format, ...)
    369 {
    370   int __retval;
    371   __builtin_va_list __local_argv; __builtin_va_start( __local_argv, __format );
    372   __retval = __mingw_vfprintf( stdout, __format, __local_argv );
    373   __builtin_va_end( __local_argv );
    374   return __retval;
    375 }
sdbbs
  • 4,270
  • 5
  • 32
  • 87

1 Answers1

1

When you use:

#define printf(fmt, ...) (0)

The preprocessor turns the code into this:
int main() {
    (0);
    return 0;
}

That free standing (0) is not allowed. However if you define it this way: #define printf(fmt, ...)

You can also use the command line definition:

"-Dprintf(fmt, ...)="

Everything works.

James Risner
  • 5,451
  • 11
  • 25
  • 47