Skip to content
Advertisement

implicit declaration of function ‘sched_setaffinity’

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

Advertisement

Answer

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