Celeritas Celeritas - 2 months ago 9
C Question

How do I get pthreads to work in Windows?

I was running into errors such as those mentioned bellow when trying to compile code containing pthreads

warning: return type defaults to 'int' [-Wreturn-type]|
|In function 'print_message_function':|
warning: control reaches end of non-void function [-Wreturn-type]|
| undefined reference to `_imp__pthread_create'|
| undefined reference to `_imp__pthread_create'|
| undefined reference to `_imp__pthread_join'|
| undefined reference to `_imp__pthread_join'|


I'm running GCC on Windows 7 but I have mingw installed. I'm using the IDE Code::Blocks and select "compile current file". Here is a screen shot of the linker settings, I'm at a loss here

codeblocks linker

UPDATE: I added
-pthread
to the "Other linker options" and it works better. There still are problems. When I compile it says

|In function 'print_message_function':|
warning: control reaches end of non-void function [-Wreturn-type]|


and when I go to run it CodeBlocks says "it appears the program has not been built yet" and when I click on "build" I am shown this error

mingw32-g++.exe -o "SimpleExample.exe" "SimpleExample.o" -static-libgcc -static-libstdc++ -pthread
mingw32-g++.exe: error: unrecognized option '-pthread'
Process terminated with status 1 (0 minutes, 0 seconds)
0 errors, 1 warnings (0 minutes, 0 seconds)


How do I fix this? I want to build/test on Windows but have the program run on a Unix environment. What is the difference between compile and build in an IDE?

Answer

It is -lpthread, not -pthread.

Edit: Libraries can be added to the compile line in a couple of ways. If we have a file called (for example) /usr/lib/libpthread.so we could include the file like this:

cc -o myprog /usr/lib/libpthread.so myprog.c

or, alternatively:

cc -o myprog -lpthread -L /usr/lib myprog.c

Since /usr/lib is a standard directory, we don't normally require the -L option. At runtime we might have to set an environment variable:

export LD_LIBRARY_PATH=/usr/lib

but again, the standard libraries are defaulted, so you don't have to use this unless you are building your own or using 3rd-party libraries.

Comments