0

In Linux (gcc) I can align a structure by

#ifndef WIN32
    #define ALIGN(size) __attribute__((aligned(size)))
#else
    #define ALIGN(size) __declspec(align(size))
#endif
struct Test {
    float buffer[12];
};
Test ALIGN(16) test;

The pointer alignment maybe defined as

#ifndef WIN32
    #define ALIGN_PTR(size) __attribute__((align_value(size)))
#endif
Test * ALIGN_PTR(16) pTest;

Question:

What is equivalent __attribute__((align_value(size))) in windows VC++ compiler?

This question should be no relevant to another solution with #pragma pack, since I think the key point is how to align the memory address that is equivalent to Linux in MSVC, but not align the struct size itself.

  • Possible duplicate of [#pragma pack effect](https://stackoverflow.com/questions/3318410/pragma-pack-effect) – 273K Apr 22 '18 at 11:56
  • I'm not sure. Is #pragma pack equivalent to _declspec(align(size)) in case that different piece of code uses different alignment size? – Changjian YU Apr 22 '18 at 12:03
  • 1
    Favor [the standard way](https://msdn.microsoft.com/en-us/library/dn956970.aspx). For old MSVC++ versions you can use `__declspec(align(12))`. – Hans Passant Apr 22 '18 at 12:10
  • It is OK to align the struct size to 12, but not valid for pointers address. That is why I asked the question posted. – Changjian YU Apr 22 '18 at 12:22
  • Well, pTest is certainly aligned to 12. But what it points to is not since you did not force alignment for the Test type. Not specific to MSVC++. You can hack it with `_aligned_malloc()`, in GCC land you'd use `aligned_alloc()`. operator new can align in C++17. – Hans Passant Apr 22 '18 at 12:44
  • It is not bad to use ```aligned_alloc()```. But I'm trying to make a library used in linux to work in windows. That library uses __attribute__((align_value(size))) to align the pointer, so I have to find an equivalent way in MSVC. – Changjian YU Apr 22 '18 at 13:05
  • To the best of my knowledge, there's no MSVC equivalent to `align_value` attribute. Since it's purely an optimization hint, and presumably MSVC doesn't support any optimizations that it might enable, you can simply define `ALIGN_PTR(size)` to nothing under Windows. – Igor Tandetnik Apr 22 '18 at 14:01
  • Yes, when I used the same align ```__declspec(align(size))``` or ```alignas(size)``` (suggested by Hans Passant) to the pointer, MSVC told me a warning that it did nothing to ```__declspec(align(size))``` or ```alignas(size)``` So the conclusion is that there is no equivalent ```__attribute__((align_value(size)))``` in MSVC? Thanks. – Changjian YU Apr 22 '18 at 23:28

0 Answers0