How to use native system architecture to define cflag in makefile with /arch:AVX512 or AVX2 or AVX

Sai Krishna 0 Reputation points
2023-12-27T07:37:49.94+00:00

Currently I have a sse code and avx512 code. I need to compile the code based on supporting architecture in the machine using a makefile.

Like to include /arch:AVX512 if CPU supports AVX instructions, else not to include that flag.

In code used the conditions based on cpuid. How to achieve the same in makefile. like the following snippet.

Note: I need compile with MSVC compiler in windows not GCC compiler.


!IFDEF OLD_COMPILER
CFLAGS_WARN_LEVEL = -W4
!ELSE
CFLAGS_WARN_LEVEL = -Wall
!ENDIF

CFLAGS = $(CFLAGS) -nologo -c -Fo$O/ $(CFLAGS_WARN_LEVEL) -WX -EHsc -Gy -GR- -GF /arch:AVX512

!IF "$(CC)" == "clang-cl"

CFLAGS = $(CFLAGS) \
  -Werror \
  -Wall \
  -Wextra \
  -Weverything \
  -Wfatal-errors \

!ENDIF

Can we automate this instead of hardcoding /arch:AVX512 flag while building or compiling itself in makefile

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,761 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Dikky Ryan Pratama 1,460 Reputation points
    2023-12-27T07:43:06.7033333+00:00

    Hi Sai Krishna,

    You can use the cpuid instruction to determine the supported architecture during runtime, and then use that information to conditionally set compiler flags in your Makefile. Here's an example Makefile:

    
    # Determine if AVX512 is supported
    
    AVX512_SUPPORTED := $(shell (echo -n "int main() { __asm__ __volatile__ (\"cpuid\" : : : \"%rax\", \"%rbx\", \"%rcx\", \"%rdx\"); return 0; }" | $(CC) -x c - -o /dev/null -march=native) && echo "1" || echo "0")
    
    # Set compiler flags based on AVX512 support
    
    ifeq ($(AVX512_SUPPORTED), 1)
    
        CFLAGS += -march=native -mavx512f -mavx512cd -mavx512bw -mavx512dq
    
    else
    
        CFLAGS += -march=native
    
    endif
    
    # Add other compiler flags as needed
    
    CFLAGS += -Wall -Wextra -Werror -Weverything -Wfatal-errors
    
    # Rest of your Makefile...
    
    

    In this example, the AVX512_SUPPORTED variable is determined using a small C program that includes inline assembly with the cpuid instruction. The result is then used to conditionally add the necessary compiler flags for AVX512 support.

    Please note that the specific compiler flags may vary depending on your compiler and platform. Adjust the flags accordingly based on your compiler documentation and requirements.

    Regards,

    4 people found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.