c linux 获取cpuid_通过C ++获取cpuid序列号

这篇博客介绍了如何在Linux环境下,使用C++通过内联汇编获取CPUID序列号。文章提到了对于不同的编译器可能需要不同的实现方式,并提供了适用于GCC编译器的示例代码,该代码展示了如何获取并打印CPUID的四个寄存器值以及解析出CPU的供应商信息。
摘要由CSDN通过智能技术生成

Your posted code will work only with the Microsoft compiler which is part of Visual Studio because it uses the Microsoft specific header file intrin.h (and stdafx.h) and the MS compiler specific __cpuid, __cpuidex[^] intrinsic function.

If you use another compiler, you must check if that provides its own support of the x86 cpuid instruction. If not, it may be implemented using inline assembly which again depends on the used compiler (if supported and syntax).

With Linux for example, there is a definition in the header file arch/x86/include/asm/processor.h which can be also used with Windows when using a compiler that uses the same inline assembly syntax like the Gnu compilers:

static inline void native_cpuid(unsigned int *eax, unsigned int *ebx,

unsigned int *ecx, unsigned int *edx)

{

/* ecx is often an input as well as an output. */

asm volatile("cpuid"

: "=a" (*eax),

"=b" (*ebx),

"=c" (*ecx),

"=d" (*edx)

: "0" (*eax), "2" (*ecx)

: "memory");

}

[EDIT]

A working example for the GCC compiler (tested with Ubuntu 14.04LTS):

#include

#include

static inline void native_cpuid(unsigned int *eax, unsigned int *ebx,

unsigned int *ecx, unsigned int *edx)

{

/* ecx is often an input as well as an output. */

asm volatile("cpuid"

: "=a" (*eax),

"=b" (*ebx),

"=c" (*ecx),

"=d" (*edx)

: "0" (*eax), "2" (*ecx)

: "memory");

}

int main()

{

int eax, ebx, ecx, edx;

eax = 0;

native_cpuid(&eax, &ebx, &ecx, &edx);

printf("EAX: %08X EBX: %08X ECX: %08X EDX: %08X\n", eax, ebx, ecx, edx);

char vendor[13];

memcpy(vendor, &ebx, 4);

memcpy(vendor+4, &edx, 4);

memcpy(vendor+8, &ecx, 4);

vendor[12] = '\0';

printf("%s\n", vendor);

return 0;

}

[EDIT]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值