如何使用gcc编译多线程代码

时间:2011-07-05 18:35:08

标签: c linux ubuntu-10.04

我已经看到给定的两个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 /包括/ NPTL   -D_REENTRANT LDFLAGS = -L / usr / lib / nptl -lpthread thread1.c

4 个答案:

答案 0 :(得分:3)

你的问题在这里得到解答

gcc: Do I need -D_REENTRANT with pthreads?

基本上你需要的只是

gcc thread1.c -o thread1 -pthread

和gcc将为您处理所有定义。

答案 1 :(得分:2)

如果您的代码没有超出pthread的外部依赖性:

gcc thread1.c -o thread1 -D_REENTRANT -lpthread

Quote

  

定义_REENTRANT会导致编译器在C库中使用多个函数的线程安全(即可重入)版本。

答案 2 :(得分:1)

几乎:

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

*FLAGS变量分别包含传递给编译器和链接器invocartion的参数。 (在你的情况下,你要一次编译和链接。)确保在你自己的目标文件之后添加库

答案 3 :(得分:1)

这两个makefile将生成两组不同的命令行参数。您只需运行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

选择你喜欢的。