简体   繁体   中英

Struct member alignment in C++/Boost

We have a project that compiles with /Zp1 , this is due to legacy and cannot be changed at the moment. We started using Boost through NuGet (package system) but soon got alignment warnings and crashes. These libraries are build using the default ( /Zp8 ) compiler option.

I've read about the ABI, and found a similar question on StackOverflow but still have some questions.

Should boost library be dependent on structure member alignments?

http://www.boost.org/development/separate_compilation.html

Some questions:

  • I've noticed Boost uses #pragma pack messages for byte alignment (compatibility?). Is Boost supposed to work with different byte alignment? Should I file a bug if I can reproduce a crash because of byte alignment?

  • How to compile Boost with /Zp1 ? Where do I add the compiler option? Is it in project-config.jam file? Any examples?

  • If it crashes because of byte alignment it is your fault.
  • boost uses #pragma pack for correctness
  • Compiling with a different byte alignment produce a complete different assemby code, so you have to compile all libraries with the same alignment.
  • If you have your boost project in visual the alignment is under Properties-> C/C+1-> Code Generation -> Struct Member Alignment . If you use another tool find how options are provided to the compiler and pass /Zp1 (or -Zp1 ).

There will be multiple functions used by boost which would require a specific byte alignment. These function may be from the boost framework itself or from microsoft libraries. The classic case will be atomic operations (ie like InterlockedIncrement ) which requires a minimum byte alignment.

If there is a structure

struct
{
  char c; 
  int a;
  volatile int b;
}

and b is used as atomic operand, The structure members alignment have to be guaranteed using #pragma pack . So boost use explicit #pragma pack for correctness .

If you can find a crash that is because Boost and your project were both compiled with a non-standard, but equal alignment, that's a bug you might want to report. Boost should be mostly alignment-agnostic, and should use explicit alignment control in the cases where it really matters. But don't report performance issues, or issues on platforms where unaligned access leads to crashes.

If you get crashes because you compiled Boost with a different alignment than your own code, that's your own fault. If you can't change your project, recompile Boost with the same alignment.

Also, you should really work towards a point where you can change your project, because compiling with a non-default alignment is a really bad idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM