diff options
author | iphydf <iphydf@users.noreply.github.com> | 2017-01-20 21:16:55 +0000 |
---|---|---|
committer | iphydf <iphydf@users.noreply.github.com> | 2017-01-28 20:49:12 +0000 |
commit | 6ae33c16cf9e37fda85d70c78b3c2779eb8ca21a (patch) | |
tree | 99c3a8c26e02039b515bb6f57d2797d1cdf77c1d /toxcore/ccompat.h | |
parent | 895de7ef26e7617769f2271345e414545c2581f8 (diff) |
Add VLA compatibility macro for C89-ish compilers.
Diffstat (limited to 'toxcore/ccompat.h')
-rw-r--r-- | toxcore/ccompat.h | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/toxcore/ccompat.h b/toxcore/ccompat.h new file mode 100644 index 00000000..e72e66ae --- /dev/null +++ b/toxcore/ccompat.h | |||
@@ -0,0 +1,43 @@ | |||
1 | /* | ||
2 | * C language compatibility macros for varying compiler support. | ||
3 | */ | ||
4 | #ifndef CCOMPAT_H | ||
5 | #define CCOMPAT_H | ||
6 | |||
7 | // Marking GNU extensions to avoid warnings. | ||
8 | #if defined(__GNUC__) | ||
9 | #define GNU_EXTENSION __extension__ | ||
10 | #else | ||
11 | #define GNU_EXTENSION | ||
12 | #endif | ||
13 | |||
14 | // Variable length arrays. | ||
15 | // VLA(type, name, size) allocates a variable length array with automatic | ||
16 | // storage duration. VLA_SIZE(name) evaluates to the runtime size of that array | ||
17 | // in bytes. | ||
18 | // | ||
19 | // If C99 VLAs are not available, an emulation using alloca (stack allocation | ||
20 | // "function") is used. Note the semantic difference: alloca'd memory does not | ||
21 | // get freed at the end of the declaration's scope. Do not use VLA() in loops or | ||
22 | // you may run out of stack space. | ||
23 | #if !defined(_MSC_VER) && __STDC_VERSION__ >= 199901L | ||
24 | // C99 VLAs. | ||
25 | #define VLA(type, name, size) type name[size] | ||
26 | #define SIZEOF_VLA sizeof | ||
27 | #else | ||
28 | |||
29 | // Emulation using alloca. | ||
30 | #ifdef _WIN32 | ||
31 | #include <malloc.h> | ||
32 | #else | ||
33 | #include <alloca.h> | ||
34 | #endif | ||
35 | |||
36 | #define VLA(type, name, size) \ | ||
37 | const size_t name##_size = (size) * sizeof(type); \ | ||
38 | type *const name = (type *)alloca(name##_size) | ||
39 | #define SIZEOF_VLA(name) name##_size | ||
40 | |||
41 | #endif | ||
42 | |||
43 | #endif /* CCOMPAT_H */ | ||