-
Notifications
You must be signed in to change notification settings - Fork 0
/
get-sizeof.sh
executable file
·108 lines (91 loc) · 1.92 KB
/
get-sizeof.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/bin/bash
set -eu
usage_and_exit() {
printf >&2 "Usage: %s [-c] [-I header-file] [-D define[=value]] c-type...\n" "$0"
printf >&2 " -c Compile in the current directory.\n"
printf >&2 " -I <file> Include this file in the C source.\n"
printf >&2 " -D <key>=<val> Include this definition in the C source.\n"
exit 1
}
[[ $# -eq 0 ]] && usage_and_exit
# Variables
c_compiler=cc
includes=()
defines=()
undefs=()
use_temp=true
# Parse arguments
while getopts ':cI:D:?' opt; do
case "$opt" in
c)
use_temp=false
;;
I)
includes+=("$OPTARG")
;;
D)
defines+=("$OPTARG")
;;
U)
undefs+=("$OPTARG")
;;
:)
printf >&2 "Option %s requires an argument\n". "$OPTARG"
usage_and_exit
;;
\?)
printf >&2 "Invalid argument: '-%s'\n" "$OPTARG"
usage_and_exit
;;
esac
done
shift "$((OPTIND - 1))"
# Create temp files
if "$use_temp"; then
c_file="$(mktemp "${TEMP_DIR:-/tmp}/XXXXXXX.c")"
c_binary="$(mktemp "${TEMP_DIR:-/tmp}/XXXXXXX")"
else
c_file="$(mktemp XXXXXXX.c)"
c_binary="$(mktemp XXXXXXX)"
fi
# Remove temp files on exit
on_exit() {
rm -f "$c_file" "$c_binary"
}
trap on_exit EXIT SIGABRT SIGINT SIGHUP SIGTERM
[[ $# -eq 0 ]] && usage_and_exit
for type in "$@"; do
cat > "$c_file" <<- EOF
#include <stdio.h>
EOF
for define in "${defines[@]}"; do
key="$(cut -d= -f1 <<< "$define")"
val="$(cut -d= -f2 <<< "$define")"
cat >> "$c_file" <<- EOF
#define $key $val
EOF
done
echo >> "$c_file"
for undef in "${undefs[@]}"; do
cat >> "$c_file" <<- EOF
#undef $undef
EOF
done
echo >> "$c_file"
for include in "${includes[@]}"; do
cat >> "$c_file" <<- EOF
#include "$include"
EOF
done
echo >> "$c_file"
cat >> "$c_file" <<- EOF
int main(void)
{
printf("sizeof($type) -> %zu\n", sizeof($type));
return 0;
}
EOF
"$c_compiler" -o "$c_binary" "$c_file" 2>/dev/null \
&& "$c_binary" \
|| printf >&2 "sizeof(%s) -> unknown\n" "$type"
done