Skip to content

Instantly share code, notes, and snippets.

@leiless
Last active February 25, 2024 16:35
Show Gist options
  • Save leiless/8b8603ae31c00fe38d2e97d94462a5a5 to your computer and use it in GitHub Desktop.
Save leiless/8b8603ae31c00fe38d2e97d94462a5a5 to your computer and use it in GitHub Desktop.
Get CPU vendor ID string (works in Linux, Windows, macOS)
#include <stdio.h>
#ifdef _WIN32
#include <intrin.h> // __cpuid()
#endif
typedef unsigned int cpuid_t[4];
#define EAX 0
#define EBX 1
#define ECX 2
#define EDX 3
// https://elixir.bootlin.com/linux/latest/source/arch/x86/include/asm/processor.h#L216
// https://stackoverflow.com/questions/6491566/getting-the-machine-serial-number-and-cpu-id-using-c-c-in-linux
// https://stackoverflow.com/questions/1666093/cpuid-implementations-in-c
static inline void native_cpuid(unsigned int function_id, cpuid_t r) {
#ifdef _WIN32
__cpuid((int *) r, (int) function_id);
#else
r[EAX] = function_id;
r[ECX] = 0;
/* ecx is often an input as well as an output. */
asm volatile("cpuid"
: "=a" (r[EAX]),
"=b" (r[EBX]),
"=c" (r[ECX]),
"=d" (r[EDX])
: "0" (r[EAX]), "2" (r[ECX])
: "memory");
#endif
}
#define VENDOR_ID_LEN 13
// XXX: you have to make sure the vendor argument is at least lengthed VENDOR_ID_LEN
static inline void cpuid_vendor_id(char vendor[VENDOR_ID_LEN]) {
// Always initialize the result in case of buggy CPU (like ES/QS CPUs)
cpuid_t v = {};
native_cpuid(0, v);
// https://learn.microsoft.com/en-us/cpp/intrinsics/cpuid-cpuidex?view=msvc-170#example
((unsigned int *) vendor)[0] = v[EBX];
((unsigned int *) vendor)[1] = v[EDX];
((unsigned int *) vendor)[2] = v[ECX];
vendor[VENDOR_ID_LEN - 1] = '\0';
}
int main(void) {
char s[VENDOR_ID_LEN];
cpuid_vendor_id(s);
printf("CPU Vendor ID: '%s'\n", s);
return 0;
}
@leiless
Copy link
Author

leiless commented Oct 26, 2022

# On an Intel CPU
$ gcc -Wall cpuid_vendor_id.c && ./a.out
CPU Vendor ID: 'GenuineIntel'

# On an AMD CPU
$ clang-7 cpuid_vendor_id.c && ./a.out
CPU Vendor ID: 'AuthenticAMD'

Useful links

https://replit.com/languages/c
https://stackoverflow.com/questions/2224334/gcc-dump-preprocessor-defines
https://www.brain-dump.org/blog/printing-all-the-pre-defined-gcc-macros/

@leiless
Copy link
Author

leiless commented Oct 27, 2022

You may also this the following code to guard the above code

// https://sourceforge.net/p/predef/wiki/Architectures/
// https://stackoverflow.com/questions/152016/detecting-cpu-architecture-compile-time/69856463#69856463
#if defined(__x86_64__) || defined(_M_X64)          // gcc || msvc

#else                                               // gcc || msvc

#endif                                              // gcc || msvc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment