Search code examples
windowsdllstatic-linkingmingw32pthreads-win32

pthreads static linking with MinGW


I would like to statically link "pthreads for Win32" with my application, compiled with MinGW32 so the app won't need pthreadGC2.dll to run.

I'm using the latest release of pthreads - 2.9.1, downloaded from here and lib and include files are copied to MinGW lib and include directories.

When searching the web how to do that I stumbled upon this thread which instructs using the -static-libgcc -static-libstdc++ flags. This doesn't work, meaning the app compiles but it can't run without pthreadGC2.dll present.

They also recommend using -static -static-libgcc -static-libstdc++. This doesn't compile with the following error:

main.o:main.cpp:(.text+0x461): undefined reference to  `_imp__pthread_create'
main.o:main.cpp:(.text+0x4be): undefined reference to `_imp__pthread_join'

Does anyone knows how to do that?

By the way - coping pthreadGC2.dll downloaded from 2.9.1 release (inside pthreads-w32-2.9.1-1-mingw32-dll.tar.lzma) to the app's folder is not enough. To run the app I should also copy another dll: libgcc_s_dw2-1.dll. This is really bad for me - I wouldn't want to make my users have these 2 DLLs each time they want to run my app

Here is my code:

#include <stdio.h>
#include <pthread.h>

static void* threadMain(void* param)
{
    printf("thread start\n");
    for (int i = 0; i < 2; i++)
        Sleep(1);
    printf("thread end\n");
    return NULL;
}

int main(int argc, char* argv[])
{
    pthread_t thread;
    int err = pthread_create(&thread, NULL, threadMain, NULL);
    if (err != 0)
    {
         printf("Cannot create thread: %s", strerror(err));
         return;
    }

    printf("thread created\n");

    Sleep(1);

    pthread_join(thread, NULL);
    printf("thread joined\n");
}

and my makefile:

all:
    g++.exe -DHAVE_STRUCT_TIMESPEC -c -o main.o main.cpp
    g++.exe -static-libgcc -static-libstdc++ -o link_pthreads.exe main.o -lpthread

clean:
    del main.o
    del link_pthreads.exe

Solution

  • With the new updated version of MinGW you can get version 2.10 of pthread-win32 library. Among several changes and bug fixes, you could find the possibility to statically link it. You only need to include -lpthread in the list of static libraries.

    Following is an example mixing static linking with the pthread library and dynamic linking with a Windows library:

    mingw32-gcc.exe -o sample.exe sample.c -Wl,-Bstatic -lpthread -Wl,-Bdynamic -lws2_32
    

    With this, you also release the dependency on libgcc_s_dw2-1.dll