Visual Studio 无法识别 __AVX2__ 或 __AVX__

问题描述 投票:0回答:1

我正在用 C++ 实现一个简单的 SIMD 包装器。 为了使其跨平台,我使用 CMake 和 Visual Studio 来设置项目

我添加了 /Arch:AVX2,但 Visual Studio 无法识别

__AVX2__
宏。

首先,我的 CMake。

cmake_minimum_required(VERSION 3.12.2)

set(INCLUDEDIR "include/Maths")
set(SOURCEDIR "src")

set(HEADER_FILES
    ${INCLUDEDIR}/export.h 
    ${INCLUDEDIR}/SIMDWrapper/Config/SIMDConfig.h)

set(SOURCE_FILES 
    ${SOURCEDIR}/Application.cpp)


add_library(Maths SHARED ${SOURCE_FILES}  ${HEADER_FILES})
target_link_libraries(Maths PUBLIC Core)
target_include_directories(Maths PUBLIC "include")
target_compile_options(Maths PRIVATE $<$<BOOL:${MSVC}>:/arch:AVX2>)
target_compile_definitions(Maths PRIVATE MATHS_EXPORT)

还有我的头文件(来自 Agner Fog 的 VectorClass

instrset.h
):

#pragma once
#if (defined(_M_AMD64) || defined(_M_X64) || defined(__amd64)) && ! 
    defined(__x86_64__)
#define __x86_64__ 1
#endif


#ifndef SIMD_INSTR_SET
#if defined (__AVX2__)
    #define SIMD_INSTR_SET 8
#elif defined ( __AVX__ )
    #define SIMD_INSTR_SET 7
#elif defined ( __SSE4_2__ )
    #define SIMD_INSTR_SET 6
#elif defined ( __SSE4_1__ )
    #define SIMD_INSTR_SET 5
#elif defined ( __SSSE3__ )
    #define SIMD_INSTR_SET 4
#elif defined ( __SSE3__ )
    #define SIMD_INSTR_SET 3
#elif defined ( __SSE2__ ) || defined ( __x86_64__ )
    #define SIMD_INSTR_SET 2 //this is where the color has changed
#elif defined ( __SSE__ )
    #define SIMD_INSTR_SET 1
#elif defined ( _M_IX86_FP )    
   #define SIMD_INSTR_SET _M_IX86_FP
#else
   #define SIMD_INSTR_SET 0
#endif // instruction set defines
#endif // SIMD_INSTR_SET

这就是我所做的。

__x86_64__
已定义,我的CPU是i5 Skylake,所以它应该支持AVX2。

我检查了是否从项目配置属性中启用了高级矢量扩展 2 选项,并且已启用。

是否需要从 CMake 或 Visual Studio 更改/添加某些内容才能使 AVX2 宏可识别?

c++ visual-c++ cmake macros simd
1个回答
1
投票

有三种方法可以为您的目标启用编译选项

/arch:AVX2
(如果您的编译器支持)。

使用生成器表达式

target_compile_options(Maths PRIVATE $<$<CXX_COMPILER_ID:MSVC>:/arch:AVX2>)

或者通过在

if
子句中设置编译选项

if(MSVC)
    target_compile_options(Maths PRIVATE /arch:AVX2)
endif()

或者使用

add_definition
调用将定义添加到在此命令之后在脚本中创建的所有目标

if(MSVC)
    add_definitions(/arch:AVX2)
endif()

如果不是绝对必要,我会尽量避免使用生成器表达式,因为它们不会提高 CMake 脚本文件的可读性,而且有时很难正确执行。

© www.soinside.com 2019 - 2024. All rights reserved.