implicit declaration of function ‘sched_setaffinity’

◇◆丶佛笑我妖孽 提交于 2019-12-23 09:06:10

问题


I'm writing a program which needed to be run on single core. To bind it to single core, I'm using sched_setaffinity(), but the compiler gives warning:

implicit declaration of function ‘sched_setaffinity’

My test code is:

#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
}

Can you please help me to figure it out. Actually code is compiled and run, but I'm not sure whether it is running on single core or is switching cores.

I'm using Ubuntu 15.10 and gcc version 5.2.1


回答1:


You need to move #define _GNU_SOURCE to a top. In man sched_setaffinity it says:

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

while in man 7 feature_test_macros it says:

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.

So at the end of the day your code should look like this:

#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
}


来源:https://stackoverflow.com/questions/36794338/implicit-declaration-of-function-sched-setaffinity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!