Cannot run app in windows build with #pragma pack(1) and sizeof (struct)
-
wrote on 22 Nov 2013, 08:57 last edited by
Hello all.
I would like to use
#pragma pack(1)
that will make the size of struct be exactly the ones that is declared. Ex:typedef struct s {
u8 a;
u16 b;
}tStruct;without #pragma pack(1)
sizeof (tStruct) == 4 (depending on platform?)with #pragma pack(1)
sizeof (tStruct) == 3but in windows, QT will assert on the internal checks of QT library complaining about alignment.
I am using QT 5.1.1 MinGW
Any suggestions how can I solve it?
Is there any way to use sizeof to return exactly the size declared of a structure?Thanks in advance.
MRL -
wrote on 22 Nov 2013, 10:01 last edited by
Hello,
I had same problem recently. With MinGW it worked with following construction:
@
struct _T1Sec
{
char command;
char reserved;
unsigned short number;
TCtrlOneDevice data[];
} attribute((gcc_struct, packed));
typedef struct _T1Sec T1Sec;
@TCtrlOneDevice is another structure.
For your case you can also check the other options for @__attribute__()@. -
wrote on 22 Nov 2013, 11:11 last edited by
I found also
__declspec(align(x))
http://msdn.microsoft.com/en-us/library/71kf49f1.aspx
but I am not sure if it works in gcc.I will try also your option.
thanks! -
You can control the scope of pack pragma like this:
@
#pragma pack(push,1)
struct S { ... };
#pragma pack(pop)
@ -
wrote on 22 Nov 2013, 12:39 last edited by
Pragma directives don't work for gcc (MinGW / g++). They are only for compilers of Microsoft and Borland. For MinGW you have to look in its documentation for alternatives. I didn't search for other directives because I didn't need to. But above structure worked for me when I converted a project from C++ Builder to Qt (MinGW).
-
@stoyanps That's not true. Some pragma directives, although non-standard, are well adapted among different compilers.
#pragma pack is supported by both gcc and mingw (I just checked on mingw 4.8.2). It's also documented "here":http://gcc.gnu.org/onlinedocs/gcc/Structure_002dPacking-Pragmas.html for gcc.
-
wrote on 22 Nov 2013, 15:51 last edited by
You are right. But when I did this research (1 year ago) I didn't notice this possibility. However now I saw that their use is not recommended: "Same site":http://gcc.gnu.org/onlinedocs/gcc/Pragmas.html#Pragmas
-
Note the wording - "in general" :) In general I agree, but...
since there's no language specified way to do this I would at least go for the extension that is supported on most platforms.
In this particular case pragmas are while attribute isn't. You would have to use some macros to target specific compiler.
6/8