且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

隐式函数声明'sched_setaffinity'

更新时间:2022-12-16 08:17:42

您需要将 #define _GNU_SOURCE 移至顶端。在 man sched_setaffinity 中表示:

  #define _GNU_SOURCE / *请参阅feature_test_macros (7)* / 

man 7 feature_test_macros $ c $注意:为了有效,在包含任何头文件之前,必须先定义一个特征测试宏
文件。这可以在
编译命令(cc -DMACRO = value)中完成,也可以在包含任何头文件之前在
中定义宏源代码。

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

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


int main()
{
unsigned long cpuMask = 2;
sched_setaffinity(0,sizeof(cpuMask),& cpuMask);
printf(Hello world);
//一些其他函数调用
}


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

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
}