Skip to content

Instantly share code, notes, and snippets.

@xqrs
Created May 15, 2026 17:07
Show Gist options
  • Select an option

  • Save xqrs/94e987d285a3bf4fa3b980a5590ba949 to your computer and use it in GitHub Desktop.

Select an option

Save xqrs/94e987d285a3bf4fa3b980a5590ba949 to your computer and use it in GitHub Desktop.
sizeof -- sizeof a C struct
#!/bin/sh --
# sizeof STRUCT [HEADER...]
set -ue
if [ "$#" = 0 ];then
cat >&2 <<-EOF
USAGE: sizeof STRUCT [HEADER...]
EXAMPLE: sizeof stat sys/stat.h
EOF
exit 1
fi
s=$1
shift
for t in struct union enum;do
{
printf '#include <%s>\n' "$@" stdio.h
printf 'int main(){printf("%%zu\\n",sizeof(struct %s));}' "$s"
} | tcc -run - 2>/dev/null && exit || :
done
{
printf '#include <%s>\n' "$@" stdio.h
printf 'int main(){printf("%%zu\\n",sizeof(%s));}' "$s"
} | tcc -run - || {
printf 'sizeof: %s: Unknown type\n' "$s"
printf 'sizeof: check headers and type name\n'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment