aligned_alloc
is defined in C11. It is not (yet) defined for C++, although it may show up in C++17. (That is, it is not in the list of (currently) 209 functions in the standard C library which are expected to be available in the standard C++ library. See Appendix C of the C++ standard.)
(Update August 2018: aligned_alloc
is indeed defined by C++17, as predicted above. So you if you have a sufficiently recent C++ compiler, you should be able to avoid all the messing around with feature-test macros by just specifying the use of C++17; for g++
and clang++
, that can be done with the -std=c++17
command-line flag.)
If you want to use it with GCC (or, more specifically, with g++), you should use the feature test macro _ISOC11_SOURCE
. Like all feature test macros, this macro must be #define
'd in every file which requires it before any #include
. [See note 1] (The feature test macro would not be necessary if you were compiling a C program with -std=c11
.)
I found the correct feature test macro from man aligned_alloc
:
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
posix_memalign(): _POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600
aligned_alloc(): _ISOC11_SOURCE
As that indicates, you can read
man 7 feature_test_macros
for more information on feature test macros, including a list of the macros recognized by glibc, and when each one applies.
The aligned_alloc
manpage also documents the very similar posix_memalign
function, which has been part of the Posix standard since Issue 6, and which has different (and more common) feature test macros, as indicated above. posix_memalign
should be portable to any Posix system, which might or might not include more systems than those that accept the use of a C11 function in C++.
Notes
- This means you shouldn't put the
#define
in a header file, since the header file cannot be included before the first include :) However, if you use something like #include "config.h"
to include platform definitions, and every source file starts with #include "config.h"
, prior to any other #include
, and the #define
occurs in config.h
prior to any #include
, you should be OK.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…