I was wondering about this specifically for building software in Debian
(the installed Debian system can be a 32-bit version with a 32 bit
kernel, libraries, etc., or it can be a 64-bit version with stuff
compiled for the 64-bit rather than 32-bit compatibility mode).
Debian packages themselves need to know what architecture they are
for (of course) when they actually create the package with all of its
metadata, including platform architecture, so there is a packaging tool
that outputs it for other packaging tools and scripts to use, called dpkg-architecture.
It includes both what it's configured to build for, as well as the
current host. (Normally these are the same though.) Example output on a
64-bit machine:
DEB_BUILD_ARCH=amd64
DEB_BUILD_ARCH_OS=linux
DEB_BUILD_ARCH_CPU=amd64
DEB_BUILD_GNU_CPU=x86_64
DEB_BUILD_GNU_SYSTEM=linux-gnu
DEB_BUILD_GNU_TYPE=x86_64-linux-gnu
DEB_HOST_ARCH=amd64
DEB_HOST_ARCH_OS=linux
DEB_HOST_ARCH_CPU=amd64
DEB_HOST_GNU_CPU=x86_64
DEB_HOST_GNU_SYSTEM=linux-gnu
DEB_HOST_GNU_TYPE=x86_64-linux-gnu
You can print just one of those variables or do a test against their values with command line options to dpkg-architecture.
I have no idea how dpkg-architecture deduces the architecture, but
you could look at its documentation or source code (dpkg-architecture
and much of the dpkg system in general are Perl).