cgnugcc-warning

How to resolve C printf %b format warnings


I am getting warning for below program

#include <stdio.h>

int main(void)
{
    int num = 0xff;
    printf("%B\n", num);
    printf("%b\n", ~num);
    printf("%b\n", ~num+1);
    return 0;
}

warning

gcc binary-format-print.c
binary-format-print.c: In function ‘main’:
binary-format-print.c:6:18: warning: unknown conversion type character ‘B’ in format [-Wformat=]
    6 |         printf("%B\n", num);
      |                  ^
binary-format-print.c:6:16: warning: too many arguments for format [-Wformat-extra-args]
    6 |         printf("%B\n", num);
      |                ^~~~~~
binary-format-print.c:7:18: warning: unknown conversion type character ‘b’ in format [-Wformat=]
    7 |         printf("%b\n", ~num);
      |                  ^
binary-format-print.c:7:16: warning: too many arguments for format [-Wformat-extra-args]
    7 |         printf("%b\n", ~num);
      |                ^~~~~~
binary-format-print.c:8:18: warning: unknown conversion type character ‘b’ in format [-Wformat=]
    8 |         printf("%b\n", ~num+1);
      |                  ^
binary-format-print.c:8:16: warning: too many arguments for format [-Wformat-extra-args]
    8 |         printf("%b\n", ~num+1);

ldd version,

❯ ldd --version
ldd (Ubuntu GLIBC 2.35-0ubuntu3.6) 2.35
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Written by Roland McGrath and Ulrich Drepper.

gcc version

❯ gcc --version
gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE

I suppose gnu C supports binary print format. Then why such warnings?

How to resolve these warning?

Thanks.


Solution

  • You need gcc 12+

    <source>: In function 'main':
    <source>:6:14: warning: ISO C does not support the '%B' gnu_printf format [-Wformat=]
        6 |     printf("%B\n", num);
          |              ^
    <source>:7:14: warning: ISO C17 does not support the '%b' gnu_printf format [-Wformat=]
        7 |     printf("%b\n", ~num);
          |              ^
    <source>:8:14: warning: ISO C17 does not support the '%b' gnu_printf format [-Wformat=]
        8 |     printf("%b\n", ~num+1);
          |              ^
    
    11111111
    11111111111111111111111100000000
    11111111111111111111111100000001
    

    With -std=c2x,

    <source>: In function 'main':
    <source>:6:14: warning: ISO C does not support the '%B' gnu_printf format [-Wformat=]
        6 |     printf("%B\n", num);
          |              ^
    
    11111111
    11111111111111111111111100000000
    11111111111111111111111100000001