This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

How to use _Generic with bit-fields


I'm using gcc 5.3.0:

$ gcc --version
gcc (GCC) 5.3.0
Copyright (C) 2015 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.


And I've tried to use _Generic to print the type of a bit field but
the compiler fails with:

$ make
gcc -Wall -std=c11 -o test.o -c test.c
test.c: In function âmainâ:
test.c:8:35: error: â_Genericâ selector of type âunsigned char:2â is
not compatible with any association
 #define type_to_str(__x) _Generic((__x), \
                                   ^
test.c:17:18: note: in expansion of macro âtype_to_strâ
   printf("%s\n", type_to_str(b.f1));
                  ^
Makefile:7: recipe for target 'test.o' failed
make: *** [test.o] Error 1
bash: ./test: No such file or directory


The test program is:

$ cat test.c
#include <stdio.h>

struct bits {
  unsigned char f0;
  unsigned char f1:2;
};

#define type_to_str(__x) _Generic((__x), \
  unsigned char : "unsigned char")

int main(void) {
  struct bits b = { .f0 = 255, .f1 = 3 };

  printf("%d\n", b.f0);
  printf("%s\n", type_to_str(b.f0));
  printf("%d\n", b.f1);
  printf("%s\n", type_to_str(b.f1));

  return 0;
}

And the Makefile is:

$ cat Makefile
CC = gcc
CFLAGS = -Wall -std=c11

all: test

test.o: test.c
$(CC) $(CFLAGS) -o test.o -c test.c

test: test.o
$(CC) $(CFLAGS) test.o -o test

clean:
rm -f test test.o test.txt


My type_to_str macro seems correct, as all is well if I comment out the last
printf:

$ cat test.c
#include <stdio.h>

struct bits {
  unsigned char f0;
  unsigned char f1:2;
};

#define type_to_str(__x) _Generic((__x), \
  unsigned char : "unsigned char")

int main(void) {
  struct bits b = { .f0 = 255, .f1 = 3 };

  printf("%d\n", b.f0);
  printf("%s\n", type_to_str(b.f0));
  printf("%d\n", b.f1);
  //printf("%s\n", type_to_str(b.f1));

  return 0;
}


It then compiles and runs successfully:

$ make
gcc -Wall -std=c11 -o test.o -c test.c
gcc -Wall -std=c11 test.o -o test
$ ./test
255
unsigned char
3


How do I create a type association for a bit field?


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]