函数‘sched_setaffinity’的隐式声明

implicit declaration of function ‘sched_setaffinity’

我正在编写一个需要 运行 在单核上运行的程序。要将它绑定到单核,我使用 sched_setaffinity(),但编译器给出警告:

implicit declaration of function ‘sched_setaffinity’

我的测试代码是:

#include <stdio.h>
#include <unistd.h>
#define _GNU_SOURCE
#include <sched.h>

int main()
{
    unsigned long cpuMask = 2;
    sched_setaffinity(0, sizeof(cpuMask), &cpuMask);
    printf("Hello world");
    //some other function calls
}

你能帮我弄清楚吗?实际上代码是编译过的 运行,但我不确定它是 运行ning on single core 还是 switching cores.

我正在使用 Ubuntu 15.10 和 gcc 版本 5.2.1

您需要#define _GNU_SOURCE移到顶部。在 man sched_setaffinity 它说:

 #define _GNU_SOURCE             /* See feature_test_macros(7) */

而在 man 7 feature_test_macros 中它说:

NOTE: In order to be effective, a feature test macro must be defined before including any header files. This can be done either in the compilation command (cc -DMACRO=value) or by defining the macro within the source code before including any headers.

所以在一天结束时,您的代码应该如下所示:

#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <sched.h>


int main()
{
    unsigned long cpuMask = 2;
    sched_setaffinity(0, sizeof(cpuMask), &cpuMask);
    printf("Hello world");
    //some other function calls
}