Last active
October 27, 2024 05:31
-
-
Save leiless/8b8603ae31c00fe38d2e97d94462a5a5 to your computer and use it in GitHub Desktop.
Get CPU vendor ID string (works in Linux, Windows, macOS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
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
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/