Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why implicit declaration of pthread_yield with -lpthread while all ok with -pthread?

I compile this code main.c in CentOS7 with gcc:

#include <pthread.h>
void* mystart(void* arg)
{
    pthread_yield();
    return(0);
}
int main(void)
{
    pthread_t pid;
    pthread_create(&pid, 0, mystart, 0);
    return(0);
}

1st compile: gcc -Wall -g main.c -pthread -o a.out
It's all OK.

2nd compile: gcc -Wall -g main.c -lpthread -o a.out
Gives

warning: implicit declaration of function 'pthread_yield' [-Wimplicit-function-declaration]

  1. Can the 2nd a.out still run correctly ?
  2. How to fix the warning without -pthread? Is sched_yield another way to yield a pthread ?
like image 936
linrongbin Avatar asked Aug 24 '15 05:08

linrongbin


2 Answers

pthread_yield() is a non-standard function which is typically enabled by defining

#define _GNU_SOURCE

While you should use -pthread for compiling, I would expect you to get the same warning with both compilations (unless -pthread defines _GNU_SOURCE which may be the case).

The correct way to fix is to not use the non-standard function pthread_yield() and use the POSIX function sched_yield() instead by including #include <sched.h>.

like image 137
P.P Avatar answered Nov 15 '22 10:11

P.P


You should use -pthread for compile and link. It not only links the library, it also sets preprocessor defines and sometimes selects a different runtime library (on Windows for example).

like image 5
Zan Lynx Avatar answered Nov 15 '22 10:11

Zan Lynx