我想我已经找到了答案。如果您使用 nvcc 生成可重定位设备代码,则 nvcc 需要链接目标文件以便正确处理设备代码链接,或者您需要通过在所有具有可重定位设备代码的目标文件上运行 nvcc 来生成单独的目标文件,并带有 ' --device-link' 标志。然后可以将这个额外的目标文件包含在外部链接器的所有其他目标文件中。
我通过在源文件列表的末尾添加一个虚拟的“link.cu”文件来调整 Can python distutils compile CUDA code? 的设置。我还为 cuda 设备链接步骤添加了 cudadevrt 库和另一组编译器选项:
ext = Extension('mypythonextension',
sources=['python_wrapper.cpp', 'file_with_cuda_code.cu', 'link.cu'],
library_dirs=[CUDA['lib64']],
libraries=['cudart', 'cudadevrt'],
runtime_library_dirs=[CUDA['lib64']],
extra_compile_args={'gcc': [],
'nvcc': ['-arch=sm_70', '-rdc=true', '--compiler-options', "'-fPIC'"],
'nvcclink': ['-arch=sm_70', '--device-link', '--compiler-options', "'-fPIC'"]
},
include_dirs = [numpy_include, CUDA['include'], 'src'])
然后,适应编译器调用的函数通过以下方式获取它:
def customize_compiler_for_nvcc(self):
self.src_extensions.append('.cu')
# track all the object files generated with cuda device code
self.cuda_object_files = []
super = self._compile
def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts):
# generate a special object file that will contain linked in
# relocatable device code
if src == 'link.cu':
self.set_executable('compiler_so', CUDA['nvcc'])
postargs = extra_postargs['nvcclink']
cc_args = self.cuda_object_files[1:]
src = self.cuda_object_files[0]
elif os.path.splitext(src)[1] == '.cu':
self.set_executable('compiler_so', CUDA['nvcc'])
postargs = extra_postargs['nvcc']
self.cuda_object_files.append(obj)
else:
postargs = extra_postargs['gcc']
super(obj, src, ext, cc_args, postargs, pp_opts)
self.compiler_so = default_compiler_so
self._compile = _compile
由于我缺乏 distutils 知识,该解决方案感觉有点骇人听闻,但它似乎有效。 :)