How to compile the multithread code with gcc

冷暖自知 提交于 2019-12-09 03:23:21

问题


I have seen the given two makefiles as follows:

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?

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


回答1:


If your code don't have external dependencies beyond pthread:

gcc thread1.c -o thread1 -D_REENTRANT -lpthread

Quote:

Defining _REENTRANT causes the compiler to use thread safe (i.e. re-entrant) versions of several functions in the C library.




回答2:


Your question is answered here

gcc: Do I need -D_REENTRANT with pthreads?

Essentially all you need is

gcc thread1.c -o thread1 -pthread

and gcc will handle all the defines for you.




回答3:


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 after your own object files.




回答4:


Those two makefiles will generate two different sets of command-line arguments. You could check it yourself just by running 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.



来源:https://stackoverflow.com/questions/6587245/how-to-compile-the-multithread-code-with-gcc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!