2012-02-06 97 views
1

我寫了一些代碼,但它編譯時似乎不工作。我試圖在Ubuntu上運行此:Pthreads編譯不起作用

#include <pthread.h> 
#include <ctype.h> 
#include <unistd.h> 

char buffer[128]; 

void *write_thread(void *args) 
{ 
    int count = *((int*)args); 
    write(STDOUT_FILENO, buffer, count); 

    pthread_exit(0); 
} 

void *toupper_thread(void *args) 
{ 
    int i; 
    int count = *((int*)args); 
    for(i = 0; i < count; i++) { 
     buffer[i] = toupper(buffer[i]); 
    } 

    pthread_t writeId; 
    pthread_create(&writeId, NULL, write_thread, &count); 

    pthread_join(writeId, NULL); 
    pthread_exit(0); 
} 

void *read_thread(void *args) 
{ 
    int count = read(STDIN_FILENO, buffer, 128); 
    pthread_t toupperId; 
    pthread_create(&toupperId, NULL, toupper_thread, &count); 

    pthread_join(toupperId, NULL); 
    //buffer[count] = 0; 

    pthread_exit(0); 

} 

int main() 
{ 
    pthread_t threadId; 
    pthread_create(&threadId, NULL, read_thread, NULL); 

    pthread_join(threadId, NULL); 
} 

,當我嘗試用gcc -pthread prob41.cgcc prob41.c -lpthread編譯它,我得到這些錯誤:

prob41.c:1:21: error: pthread.h: No such file or directory 
    prob41.c: In function ‘toupper_thread’: 
    prob41.c:23: error: ‘pthread_t’ undeclared (first use in this function) 
    prob41.c:23: error: (Each undeclared identifier is reported only once 
    prob41.c:23: error: for each function it appears in.) 
    prob41.c:23: error: expected ‘;’ before ‘writeId’ 
    prob41.c:24: error: ‘writeId’ undeclared (first use in this function) 
    prob41.c: In function ‘read_thread’: 
    prob41.c:33: error: ‘pthread_t’ undeclared (first use in this function) 
    prob41.c:33: error: expected ‘;’ before ‘toupperId’ 
    prob41.c:34: error: ‘toupperId’ undeclared (first use in this function) 
    prob41.c: In function ‘main’: 
    prob41.c:45: error: ‘pthread_t’ undeclared (first use in this function) 
    prob41.c:45: error: expected ‘;’ before ‘threadId’ 
    prob41.c:46: error: ‘threadId’ undeclared (first use in this function) 

我不知道我在做什麼錯誤。

+1

有你的libc6-dev的安裝? – rekire 2012-02-06 22:14:56

回答

1

需要在編譯命令加上-I標誌,以使編譯器能夠找到pthread.h

+0

他寫了這個「gcc prob41.c -lpthread」,裏面有'-l'。 – rekire 2012-02-06 22:18:12

+0

這是一個首都,不只是-l國旗! – 2012-02-07 07:17:40

3

看來你錯過了一些依賴。

試試這個:

$ sudo apt-get install -y libc6-dev 
+0

我試過了,結果如下:升級0次,新安裝0次,刪除0次,未升級33次。 – Lara 2012-02-06 22:32:02

+0

試試這個:sudo apt-get install build-essential – rekire 2012-02-06 22:35:14

+0

仍然不起作用,同樣的錯誤 – Lara 2012-02-06 22:38:31

1
  • 您不必在系統中的pthread.h庫。嘗試安裝適合它的 庫。
  • 你需要確保使用#include <sys/type.h>
  • 不要忘記添加-lpthread在編譯:gcc -lpthread {x}.c -o {y}