c++gccclangopenmpclang++

Link the OpenMP library statically in C/C++


I have a simple C++ program that does nothing:

int main() { return 0; }

I am trying to build this program completely statically using the following command:

g++ -o c c.cc -static

Everything works fine. However, when I try to link OpenMP, which is not actually a library, using the -fopenmp flag in static mode like this:

g++ -o c c.cc -fopenmp -static

The compiler gives an error:

/usr/bin/ld: cannot find -lgomp: No such file or directory
collect2: error: ld returned 1 exit status

This issue occurs with clang++ as well. The same happens with gcc and g++. However, other libraries that have static versions, such as curl, link correctly in static mode.

(I am on Arch Linux)


Solution

  • Your system is missing the static version of the GNU OMP runtime, libgomp.a. Archlinux does not package it. Unlike most distros, Archlinux doesn't do development packages as distinct from runtime packages. The shared library version, only, is installed by package gcc-libs. To get the static version built on Archlinux you would need to build GCC from source, which may be too high a price. You've nothing to lose by seeing if some other distro's build for the same architecure will work. You could try downloading, say, the GCC 13 Ubuntu x86_64 development package that contains it such as:

    libgcc-13-dev_13.3.0-6ubuntu2~24.04_amd64.deb 
    

    from:

    http://security.ubuntu.com/ubuntu/pool/main/g/gcc-13/
    

    into your downloads directory. Or similarly for whatever GCC version you've got. Then extract it (it is actually an ar.tar.zst archive):

    ar -x libgcc-13-dev_13.3.0-6ubuntu2~24.04_amd64.deb
    tar -xf data.tar.zst
    

    which will extract ./usr in the current directory. You will find lbgomp.a at:

    ./usr/lib/gcc/x86_64-linux-gnu/13/libgomp.a
    

    Copy that libgomp.a to your build directory, then see how you fare by linking:

    $ g++ -o c c.cc -fopenmp -static -L. -lgomp
    

    Or I should say, see how you fare when you actually put some omp code in the program.

    Don't have archlinux; haven't tried it.