如何使用SSE编译一个特定的类

时间:2015-01-23 08:53:01

标签: c++ gcc sse

我有两个类做同样的事情,但是一个使用SSE4.2而另一个不使用SSE4.2。我已经检测到代码是否运行在支持SSE4.2的CPU上并使用相应的类,但我正在努力编译SSE4.2类。

我希望编译器仅对此类使用SSE4.2优化而不是其余代码,因此我无法使用-msse4.2

我读了#pragma GCC target("sse4.2"),但我在包含的SSE4.2-Header中仍然遇到编译错误:

nmmintrin.h:31:3: error: #error "SSE4.2 instruction set not enabled"

如何在启用SSE4.2选择的情况下编译此类并禁用其余代码?

我正在使用GCC 4.8& Android NDK 10d。

我的班级看起来像这样:

#include "MyClassWithSSE42.h"

#pragma GCC target("sse4.2")
#include <nmmintrin.h>

uint32_t MyClassWithSSE42::CRC32byte(const uint32_t *p, const uint32_t startValue)
{
    uint32_t c = _mm_crc32_u32(startValue, p[0]);
    c = _mm_crc32_u32(c, p[1]);
    c = _mm_crc32_u32(c, p[2]);
    c = _mm_crc32_u32(c, p[3]);
    c = _mm_crc32_u32(c, p[4]);
    c = _mm_crc32_u32(c, p[5]);
    c = _mm_crc32_u32(c, p[6]);
    return _mm_crc32_u32(c, p[7]);
}

2 个答案:

答案 0 :(得分:1)

我不知道Android工具链,但在桌面上我会在单独的目标文件中编译该类,并将其与其余代码链接。

g++ -msse4.2 -c MyClassWithSSE42.c++ -o MyClassWithSSE42.o # Compile only
g++ your_other_files.c++ MyClassWithSSE42.o                # Compile and link

答案 1 :(得分:0)

所以我尝试了GCC 4.9,因为Marc Glisse提到了它,我开始工作了!工作代码现在看起来像这样:

#include "MyClassWithSSE42.h"

__attribute__((target("sse4.2")))
uint32_t MyClassWithSSE42::CRC32byte(const uint32_t *p, const uint32_t startValue)
{
    uint32_t c = _mm_crc32_u32(startValue, p[0]);
    c = _mm_crc32_u32(c, p[1]);
    c = _mm_crc32_u32(c, p[2]);
    c = _mm_crc32_u32(c, p[3]);
    c = _mm_crc32_u32(c, p[4]);
    c = _mm_crc32_u32(c, p[5]);
    c = _mm_crc32_u32(c, p[6]);
    return _mm_crc32_u32(c, p[7]);
}

不再需要包含<nmmintrin.h>,但我必须添加目标属性才能将其编译。