Search code examples
carraysgccalignmenttypedef

alignment of a c array - alignment of array elements is greater than element size


Consider the following C code:

typedef __attribute__((aligned(16))) signed int    INT32;

int main(int argc, char* argv[], char* envp[]) 
{
    INT32                   my_array[255];
    return 0;
}

Compiling it returns the error:

alignment_problem.c: In function ‘main’:
alignment_problem.c:7:2:error: alignment of array elements is greater than element size
INT32                   my_array[255];

I have a program that's not compiling due to this error.

Is there a way to define INT32 in a way that the alignment will work?

I am aware that clang compiles this code without error, but I would like to know if there is a way to compile the code with gcc.

EDIT: The problem is, that the typedef INT32 is one of a big program. So the solution I am searching for is to alter the definition of INT32, so that the program will compile and run.


Solution

  • The error is because you're trying to align int not the array. Options you have is that you can make a typedef with known number of elements in array and align it accordingly.

    typedef signed int  INT32[255] __attribute__((aligned(16)));
    
    int main(int argc, char* argv[], char* envp[]) 
    {
        INT32                   my_array;
        return 0;
    }
    

    or you can align it each time you use an array that needs to be aligned.

    int main(int argc, char* argv[], char* envp[]) 
    {
        signed int my_array[255] __attribute__((aligned(16)));
        return 0;
    }