如何包含Linux头文件,例如linux / getcpu.h?

Der*_*unk 1 c linux include-path

我正在使用Linux 3.5.0-17-generic #28-Ubuntu SMP Tue Oct 9 19:31:23 UTC 2012 x86_64 GNU/Linux,我需要#include<linux/getcpu.h>。编译器抱怨找不到文件。Linux的头文件在哪里?

Ser*_* L. 6

简短的答案:通常,您不直接包含这些标头。

其中的大多数OS / Machine特定标头都会自动包含在更通用的标头中。那些不是仅Linux功能,可能对于您正在运行的版本可用,也可能不可用。

至于getcpu,有一个更标准的版本称为sched_getcpusched.h具有相同的功能。

或者,您可以测试系统调用在您的系统上是否可用,然后手动调用它:

#define _GNU_SOURCE  
#include <unistd.h>
#include <sys/syscall.h>

static inline int getcpu() {
    #ifdef SYS_getcpu
    int cpu, status;
    status = syscall(SYS_getcpu, &cpu, NULL, NULL);
    return (status == -1) ? status : cpu;
    #else
    return -1; // unavailable
    #endif
}
Run Code Online (Sandbox Code Playgroud)

#include <errno.h>如果syscall返回-1,则变量errno()给出错误代码。