无法解析的外部符号 “__declspec(dllimport) struct _object * THPVariableClass“ (Windows端)

在 visual studio 或者基于 cmake 构建的项目中,利用pybind11 生成包含了 torch 的库时,出现:

[build]  error LNK2001: 无法解析的外部符号 "__declspec(dllimport) struct _object * THPVariableClass" (__imp_?THPVariableClass@@3PEAU_object@@EA) [D:\Desktop\ExtensionOPs-master\demo\build\test_cpp.vcxproj]
[build]  error LNK2001: 无法解析的外部符号 "__declspec(dllimport) struct _object * __cdecl THPVariable_Wrap(class at::TensorBase)" (__imp_?THPVariable_Wrap@@YAPEAU_object@@VTensorBase@at@@@Z) [D:\Desktop\ExtensionOPs-master\demo\build\test_cpp.vcxproj]

但利用 python 的 setuptools 进行构建时却没有问题。
查阅了 torch.utils.cpp_extension 中 CUDAExtension 模块的 cpp_extension.py 中的代码后,发现了下面这段:

def CppExtension(name, sources, *args, **kwargs):
    r'''
    Creates a :class:`setuptools.Extension` for C++.

    Convenience method that creates a :class:`setuptools.Extension` with the
    bare minimum (but often sufficient) arguments to build a C++ extension.

    All arguments are forwarded to the :class:`setuptools.Extension`
    constructor.

    Example:
        >>> from setuptools import setup
        >>> from torch.utils.cpp_extension import BuildExtension, CppExtension
        >>> setup(
                name='extension',
                ext_modules=[
                    CppExtension(
                        name='extension',
                        sources=['extension.cpp'],
                        extra_compile_args=['-g']),
                ],
                cmdclass={
                    'build_ext': BuildExtension
                })
    '''
    include_dirs = kwargs.get('include_dirs', [])
    include_dirs += include_paths()
    kwargs['include_dirs'] = include_dirs

    library_dirs = kwargs.get('library_dirs', [])
    library_dirs += library_paths()
    kwargs['library_dirs'] = library_dirs

    libraries = kwargs.get('libraries', [])
    libraries.append('c10')
    libraries.append('torch')
    libraries.append('torch_cpu')
    libraries.append('torch_python')
    kwargs['libraries'] = libraries

    kwargs['language'] = 'c++'
    return setuptools.Extension(name, sources, *args, **kwargs)

可以看到构建时链接了 ‘c10’,‘torch’,‘torch_cpu’,‘torch_python’。
于是尝试找到 “torch_python.lib” 并将其链接到项目构建中,问题解决。。。

你可能感兴趣的:(windows,c++,开发语言,pytorch)