You can selectively statically link certain libraries by providing certain linker options. For libgomp it would be something like:
gcc -o executable foo.o bar.o -Wl,-static -lgomp -Wl,-Bdynamic -lpthread -lother -llibs
Any library listed between -Wl,-static and -Wl,-Bdynamic will be linked in statically. -fopenmp should not be present in the linking command as it expands to linker flags that get appended after the user supplied options, and therefore libpthread should be listed explicitly. It also means that even simple OpenMP programs have to be compiled and linked in two separate steps for static linking to work.
Example:
// foo.c
#include <stdio.h>
#include <omp.h>
int main(void)
{
#pragma omp parallel
printf("Hello world from thread %d\n", omp_get_thread_num());
return 0;
}
Traditional compilation:
$ gcc -fopenmp -o foo foo.c
$ ldd foo
linux-vdso.so.1 => (0x00007ffff5661000)
libgomp.so.1 => /usr/lib64/libgomp.so.1 (0x0000003bcfa00000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x0000003bc2600000)
libc.so.6 => /lib64/libc.so.6 (0x0000003bc1e00000)
librt.so.1 => /lib64/librt.so.1 (0x0000003bc3200000)
/lib64/ld-linux-x86-64.so.2 (0x0000003bc1a00000)
The program is linked against the DSO version of libgomp.
Fully static linking:
$ gcc -fopenmp -static -o foo foo.c
$ ldd foo
not a dynamic executable
With -static all libraries are linked in statically into the executable.
Linking only libgomp statically:
$ gcc -fopenmp -c foo.c
$ gcc -o foo foo.o -Wl,-static -lgomp -Wl,-Bdynamic -lpthread
$ ldd foo
linux-vdso.so.1 => (0x00007ffdaaf61000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x0000003bc2600000)
libc.so.6 => /lib64/libc.so.6 (0x0000003bc1e00000)
/lib64/ld-linux-x86-64.so.2 (0x0000003bc1a00000)
It is important to maintain the correct order of statically linked objects in that case. If foo.o is placed after -lgomp, a link error results:
$ gcc -o foo -Wl,-static -lgomp -Wl,-Bdynamic foo.o -lpthread
foo.o: In function `main':
foo.c:(.text+0x14): undefined reference to `GOMP_parallel_start'
foo.c:(.text+0x23): undefined reference to `GOMP_parallel_end'
foo.o: In function `main.omp_fn.0':
foo.c:(.text+0x3b): undefined reference to `omp_get_thread_num'
collect2: ld returned 1 exit status
Any object file resulting from source code that contains OpenMP constructs should be placed before -lgomp.