See how C structures are packed during assembly

Is there a way to see how C structures are packed during assembly? I read several similar posts on how to structure packages:

But I am wondering if there is some kind of generated build time file that shows me how the structure is structured? I tried to check the mapping file created by the linker, but it does not have this information.

PS: I try to get several microcontrollers to communicate with each other via UART and because one of them is 16 bits and the other 32 bits, I hit several errors every time I update these structures.

+6
source share
1 answer

The preprocessor cannot calculate the structure offsets, so no number of macros will allow you to reset your offsets.

If you create inline objects, you can probably create .bin files (not elf, coff, mach-o). If you use each of your target compilers to create an array of offsets in an object file, and then upload it to a bin file, it should be possible to compare bin files for each of your goals. It would be nice to automate the build time verification process.

Here is an example of what I am saying:

#include <stdint.h> #include <stddef.h> typedef struct s1{ uint16_t f1; uint32_t f2; uint64_t f3; int8_t f4[5]; uint32_t f5[2]; }s1; #define o(f) ((int32_t)offsetof(s1,f)) int32_t offsets[]={ o(f1), o(f2), o(f3), o(f4), o(f5) }; 

It just creates an offset table. Build it for mipsel and x86_64 and compare. Here is the make file:

 T1:=x86_64-linux-gnu CC1:=$(T1)-gcc OBJCPY1:=$(T1)-objcopy T2:=mipsel-linux CC2:=$(T2)-gcc OBJCPY2:=$(T2)-objcopy .PHONY: all cmp clean hexdumps all: hexdumps hexdumps: hexdump.$(T1).txt hexdump.$(T2).txt hexdump.$(T1).txt: offsets.$(T1).bin hexdump -C $< > $@ hexdump.$(T2).txt: offsets.$(T2).bin hexdump -C $< > $@ offsets.$(T1).bin: offsets.$(T1).o $(OBJCPY1) -j.data -O binary $< $@ offsets.$(T2).bin: offsets.$(T2).o $(OBJCPY2) -j .data -O binary $< $@ offsets.$(T1).o: offsets.c $(CC1) -Wall -c -o $@ $< offsets.$(T2).o: offsets.c $(CC2) -Wall -c -o $@ $< clean: -rm -f offsets.$(T1).o offsets.$(T2).o -rm -f offsets.$(T1).bin offsets.$(T2).bin -rm -f hexdump.$(T1).txt hexdump.$(T2).txt 

Now comparing the offsets is pretty simple:

 evaitl@evbb ~/se $ cat hexdump.mipsel-linux.txt 00000000 00 00 00 00 04 00 00 00 08 00 00 00 10 00 00 00 |................| 00000010 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 00000020 evaitl@evbb ~/se $ cat hexdump.x86_64-linux-gnu.txt 00000000 00 00 00 00 04 00 00 00 08 00 00 00 10 00 00 00 |................| 00000010 18 00 00 00 |....| 00000014 

The mix generates a 32-byte data section instead of the x86 20 byte. If you set the size offsets , you can use cmp to compare the two in your assembly.

If your goals have different endianess, you may need to modify the o macro to use ntohl or some of them so that both compilers can emit integers in the same format.

+1
source

All Articles