Linux 如何用gcc编译多线程代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6587245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compile the multithread code with gcc
提问by q0987
I have seen the given two makefiles as follows:
我已经看到给定的两个 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
Without using makefile, what is the correct command line to compile the thread1.c with gcc?
在不使用 makefile 的情况下,使用 gcc 编译 thread1.c 的正确命令行是什么?
gcc -o thread1 CFLAGS=-I/usr/include/nptl -D_REENTRANT LDFLAGS=-L/usr/lib/nptl -lpthread thread1.c
gcc -o thread1 CFLAGS=-I/usr/include/nptl -D_REENTRANT LDFLAGS=-L/usr/lib/nptl -lpthread thread1.c
采纳答案by karlphillip
If your code don't have external dependencies beyond pthread:
如果您的代码没有 pthread 之外的外部依赖项:
gcc thread1.c -o thread1 -D_REENTRANT -lpthread
报价:
Defining _REENTRANT causes the compiler to use thread safe (i.e. re-entrant) versions of several functions in the C library.
定义_REENTRANT 会导致编译器使用C 库中几个函数的线程安全(即可重入)版本。
回答by Kerrek SB
Almost:
几乎:
gcc -o thread1 -I/usr/include/nptl -D_REENTRANT -L/usr/lib/nptl thread1.c -lpthread
The *FLAGS
variables contain the arguments that are passed to the compiler and linker invocartion, respectively. (In your case you're compiling and linking in one go.) Make sure to add libraries afteryour own object files.
该*FLAGS
变量包含分别传递到编译器和链接器invocartion的参数。(在您的情况下,您是一次性编译和链接的。)确保在您自己的目标文件之后添加库。
回答by Carl Norum
Those two makefiles will generate two different sets of command-line arguments. You could check it yourself just by running make
:
这两个 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
Choose your favourite.
选择你最喜欢的。
回答by JohnKlehm
Your question is answered here
您的问题在这里得到解答
gcc: Do I need -D_REENTRANT with pthreads?
gcc:我需要 -D_REENTRANT 和 pthreads 吗?
Essentially all you need is
基本上所有你需要的是
gcc thread1.c -o thread1 -pthread
gcc thread1.c -o thread1 -pthread
and gcc will handle all the defines for you.
gcc 将为您处理所有定义。