Reputation: 92
I want to detect the CPU architecture at runtime in a Linux environment, I've looked at getauxval(AT_PLATFORM)
but sadly it's not portable since it's relatively new. Would there be an alternative to getauxval(AT_PLATFORM)
? I could parse /proc/cpuinfo
but figured that there might be an easier way. I'm trying to get output similar to uname -m
.
Upvotes: 3
Views: 996
Reputation: 12708
If you have a program that has to be built on different architectures, and needs a build system that specifies different code for different architectures, it would be simple to add some defined constant that allows you to evaluate in which system it has been built and check that constant inside the program.
On the contrary, if your program is portable enough to be built without any change on different (most) architectures, you'll probably will not need to know in which of these architectures it has been built.
This was probably the schema followed historically to address the problem. I don't think you can solve this in a portable way, if your program can be built in non-linux system (e.g. BSD or QNX)
Upvotes: 0
Reputation: 5512
I'm trying to get output similar to uname -m.
Why not look at how uname
does it? Run apt source coreutils
and in src/uname.c
:
...
while ((c = getopt_long (argc, argv, "asnrvmpio",
uname_long_options, NULL)) != -1)
...
case 'm':
toprint |= PRINT_MACHINE;
and
if (uname (&name) == -1)
...
if (toprint & PRINT_MACHINE)
print_element (name.machine);
(notice the usage of the uname
function).
uname
is a syscall defined by POSIX and wrapped in glibc:
#include <sys/utsname.h>
int uname(struct utsname *buf);
and will store the machine hardware identifier in buf->machine
, which is what's printed by uname -m
.
As an aside - in lib/uname.c
you can see coreutils' implementation of a custom uname
function for Windows systems (which don't support the uname
syscall). This implementation uses the GetVersionEx
and GetSystemInfo
WinAPIs which provide similar functionality.
Upvotes: 4