编译器找不到'aligned_alloc'函数

时间:2018-10-12 10:07:24

标签: c++ macos gcc clang c++17

我正在尝试从aligned alloc启动示例代码:

#include <cstdio>
#include <cstdlib>

int main()
{
    int* p1 = static_cast<int*>(std::malloc(10*sizeof *p1));
    std::printf("default-aligned address:   %p\n", static_cast<void*>(p1));
    std::free(p1);

    int* p2 = static_cast<int*>(std::aligned_alloc(1024, 1024));
    std::printf("1024-byte aligned address: %p\n", static_cast<void*>(p2));
    std::free(p2);
}

我的编译器给我这个错误:

$ g++-mp-8 main.cpp -std=c++17
main.cpp:10:38: error: no member named 'aligned_alloc' in namespace 'std'
    int* p2 = static_cast<int*>(std::aligned_alloc(1024, 1024));

我正在使用macOS High Sierra 10.13.6,并尝试使用Macport的GCC 7.3.0、8.2.0和CLang(Apple LLVM版本10.0.0)编译此代码,它们都产生相同的错误。

编辑:存在std::或不存在的情况下都无法使用。

Edit2:我安装了macOS Mojave,但无法解决问题。我希望它会重新安装macOS的工具链,但没有。因此,我想我不能接受提供的答案,直到我得到更具体的答案为止。

2 个答案:

答案 0 :(得分:3)

我没有使用macOS,但是在使用自定义g ++的Linux上也遇到了类似的问题。如果您查看cstdlib标头,则类似

#if __cplusplus >= 201703L && defined(_GLIBCXX_HAVE_ALIGNED_ALLOC)
  using ::aligned_alloc;
#endif

因此,只有在C ++ 17可用且glibcxx支持它的情况下,aligned_alloc才被拉入std命名空间。如果定义了x86_64-linux-gnu/bits/c++config.h,则可以检查_GLIBCXX_HAVE_ALIGNED_ALLOC(或在macOS上类似的东西)。如果不是,则您的glibc版本太旧了。

对于clang和libc ++实现,如果定义了aligned_alloc,则_LIBCPP_HAS_C11_FEATURES可用,这又取决于glibc的最新版本。

您也可以使用boost

答案 1 :(得分:0)

正如接受的答案所提到的那样,使用boost::align::aligned_alloc解决了这个问题。

要在不进行源代码修改的情况下修复错误,只需在文件顶部添加以下内容:

#ifdef __APPLE__
#include <boost/align/aligned_alloc.hpp>
using boost::alignment::aligned_alloc;
#endif
相关问题