Libtorch static library

Hello I am building libtorch has static library. But now I am struggling to have a binary code running properly.

So I try few stuff:

  1. Just linking my main.cpp with all the static library from libtorch
    –> Result : abort libc++aby.dylib: terminating with uncaught exception of type c10::bad_optionnal_access

  2. I was suspecting it could be because I need to use whole_archive, I put all the library with whole_archive but few issue:
    –> undefined reference of onnxifi_loader
    2.1) I copy the missing libonnxifi_loader.a
    –> exec format error: my_torch_sample

I am not sure what should I do next, any suggestion how to use Libtorch as a static library ?


1 Like

After fighting few hours, I finally figure out the trouble with the static library of pytorch.
The main trouble was the --force-load or --whole-archive need to be apply on some specific library not only torch but not all of them.

Now I am able to run libtorch with and without Cuda over:
OSX Catalina (CPU)
OSX High Sierra (CPU/GPU)
Ubuntu 18.04 (CPU/GPU)

I am facing another issue now on Windows. The build failed because of this error :
error C2338: CopyToCPU requires fundamental types
If someone has an idea how to fix it, that will be very nice.


After looking to the pytorch issues it seems there is a patch for this one but not inside the latest release.

I apply it and its now build fine but still failed to link because of size:

Fatal error LNK1248: image size exceeds maximum allowable

I am building with ninja in release, I am not sure how I can fix this one, any suggestion.


Would you please try whether set MSVC_Z7_OVERRIDE=OFF works?

Hi @peterjc123,

I try to set MSVC_Z7 but still have the same issue, finally I am building torch using MinSizeRel and it seems to be working fine, I was able to build a cpu version of torch for windows 10.

Currently building the GPU version.


I was finally able to build my static windows version of torch using cuda.
Unfortunately now I have another issue.

If I link the library normally I can run my sample but I received an exception from CUDA when I try to use it. It make sense because I need to use the link flag WHOLE_ARCHIVE.

But if I use it with my static library torch. When I try to launch my executable I have a direct segfault.

Someone has an idea why torch will give me a segfault like that, I will try to have mode info why is giving a segfault but if someone have an idea it will be really useful.