Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 609
Techie Fort Avatar asked Apr 22 '16 12:04

Techie Fort


People also ask

What is implicit declaration of function?

If a name appears in a program and is not explicitly declared, it is implicitly declared. The scope of an implicit declaration is determined as if the name were declared in a DECLARE statement immediately following the PROCEDURE statement of the external procedure in which the name is used.

How do you fix an implicit function declaration?

Solution of Implicit declaration of function 1) If you are using pre-defined function then it is very likely that you haven't included the header file related to that function. Include the header file in which that function is defined.


1 Answers

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
}
like image 112
Arkadiusz Drabczyk Avatar answered Oct 13 '22 00:10

Arkadiusz Drabczyk