【问题标题】:Visual Studio not recognizing __AVX2__ or __AVX__Visual Studio 无法识别 __AVX2__ 或 __AVX__
【发布时间】:2019-01-09 16:18:45
【问题描述】:

我正在用 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。

我已检查是否从项目配置属性中启用了 Advanced Vector Extensions 2 选项,并且已启用。

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

【问题讨论】:

  • 尝试将#error test 语句添加到__AVX2__ 子句并构建以查看它是否真的设置了。根据您正在运行的 Visual Studio 的确切版本,IntelliSense 编译器有时(过于频繁)有点落后于实际的 C++ 编译器,因此您可能会得到错误的着色结果。此外,在 Visual Studio 2013 Update 2 中添加了对 /arch:AVX2 的支持。您实际使用的是哪个版本的 Visual Studio?
  • 您好!抱歉回复晚了,我用的是 VS 2017(2018 年 12 月 18 日更新)。
  • @ChuckWalbourn 是的,根本没有设置 #error 指令 AVX 的 E0035。
  • 我会检查你的命令行输出然后看看那里的结果......
  • 如果 __AVX2__ 没有定义,那么你就不能使用 /arch:AVX2 和 Visual C++ 或 Intel 编译器构建。

标签: c++ visual-c++ cmake macros simd


【解决方案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_definition(/arch:AVX2)
endif()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 2020-03-22
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多