簡體   English   中英

如何用 gcc 編譯多線程代碼

[英]How to compile the multithread code with gcc

我已經看到給定的兩個makefile如下:

all: thread1 thread2 thread3

CFLAGS=-I/usr/include/nptl -D_REENTRANT
LDFLAGS=-L/usr/lib/nptl -lpthread

clean:
    rm -f thread1 thread2 thread3

######################

all: thread1 thread2 thread3

CFLAGS=-D_REENTRANT
LDFLAGS=-lpthread

clean:
    rm -f thread1 thread2 thread3

在不使用 makefile 的情況下,使用 gcc 編譯 thread1.c 的正確命令行是什么?

gcc -o thread1 CFLAGS=-I/usr/include/nptl -D_REENTRANT LDFLAGS=-L/usr/lib/nptl -lpthread thread1.c

你的問題在這里得到解答

gcc:我需要 -D_REENTRANT 和 pthreads 嗎?

基本上你只需要

gcc thread1.c -o thread1 -pthread

gcc 將為您處理所有定義。

如果您的代碼沒有 pthread 之外的外部依賴項:

gcc thread1.c -o thread1 -D_REENTRANT -lpthread

報價

定義 _REENTRANT 會使編譯器使用 C 庫中幾個函數的線程安全(即可重入)版本。

幾乎:

gcc -o thread1 -I/usr/include/nptl -D_REENTRANT -L/usr/lib/nptl thread1.c -lpthread

*FLAGS變量分別包含傳遞給編譯器的 arguments 和 linker 調用。 (在您的情況下,您正在編譯和鏈接一個 go。)確保在您自己的 object 文件之后添加庫。

這兩個 makefile 將生成兩組不同的命令行 arguments。 您可以通過運行make自己檢查:

$ make -f makefile1
cc -I/usr/include/nptl -D_REENTRANT  -L/usr/lib/nptl -lpthread  thread1.c   -o thread1
$ make -f makefile2
cc -D_REENTRANT  -lpthread  thread1.c   -o thread1

選擇你最喜歡的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM