gpt4 book ai didi

c++ - Cuda中的链接错误

转载 作者:行者123 更新时间:2023-11-30 04:09:12 26 4
gpt4 key购买 nike

我在尝试构建基本的 cuda/thrust 代码以更熟悉 GPU 编程时遇到问题。我可能没有正确编译它,所以我想知道我做错了什么?

我正在使用以下说明进行构建

nvcc -c gpu_functions.cu
nvcc gpu_functions.o gpu_test.cu -o gpu_test

但是我收到一个链接错误:

jim@pezbox:~/dev/analytics/src$ nvcc gpu_functions.o gpu_test.cu -o gpu_test
/tmp/tmpxft_00002383_00000000-14_gpu_test.o: In function `main':
tmpxft_00002383_00000000-3_gpu_test.cudafe1.cpp:(.text+0x6e): undefined reference to `void add<thrust::device_vector<int, thrust::device_malloc_allocator<int> > >(thrust::device_vector<int, thrust::device_malloc_allocator<int> > const&, thrust::device_vector<int, thrust::device_malloc_allocator<int> > const&, thrust::device_vector<int, thrust::device_malloc_allocator<int> >&)'
collect2: ld returned 1 exit status

我有三个文件:

  1. gpu_functions.h(GPU 函数的头函数)
  2. gpu_functions.cu(GPU 函数的实现)
  3. gpu_test.cu(调用我定义的 GPU 函数的主循环)

gpu_functions.h

template<typename Vector>
void add(const Vector& in1, const Vector& in2, Vector& out);

gpu_functions.cu

#include "gpu_functions.h"
#include <thrust/sequence.h>
#include <thrust/transform.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>
#include <thrust/fill.h>
#include <thrust/replace.h>
#include <thrust/functional.h>

using namespace thrust;

template<typename Vector>
void add(const Vector& in1, const Vector& in2, Vector& out) {
transform(in1.begin(), in1.end(), in2.begin(), out.begin(),
plus<typename Vector::value_type>());
}

gpu_test.cu

#include "piston_functions.h"
#include <thrust/device_vector.h>
#include <iostream>
#include <stdio.h>

using namespace thrust;

int main(void) {
const int n = 100000000;
// allocate three device_vectors with 10 elements
device_vector<int> in1(n, 1);
device_vector<int> in2(n, 2);
device_vector<int> out(n, 0);

add(in1, in2, out);

thrust::copy(out.begin(), out.begin()+10, std::ostream_iterator<int>(std::cout,"\n"));

return 0;
}

我可能正在做一些愚蠢的事情,或者我错过了一些非常明显的事情。

最佳答案

模板函数一旦声明,就需要显式或隐式实例化,即为模板参数的特定组合生成具体函数(实例)。

gpu_functions.cu 编译单元中,您缺少两者。换句话说,编译器不会生成函数 add 的实例,因此链接器找不到要链接的任何内容。

您应该通过在隐式实例化它的位置包含模板化函数声明来解决此问题,即包含 main 函数的编译单元。

换句话说,下面的代码将正确编译

#include <thrust/device_vector.h>
#include <iostream>
#include <stdio.h>

using namespace thrust;

template<typename Vector>
void add(const Vector& in1, const Vector& in2, Vector& out) {
transform(in1.begin(), in1.end(), in2.begin(), out.begin(),
plus<typename Vector::value_type>());
}

int main(void) {
const int n = 100000000;
device_vector<int> in1(n, 1);
device_vector<int> in2(n, 2);
device_vector<int> out(n, 0);

add(in1, in2, out);

thrust::copy(out.begin(), out.begin()+10, std::ostream_iterator<int>(std::cout,"\n"));

return 0;
}

当然,您可以将模板化函数声明移动到单独的 .cuh 文件中,并通过 #include 指令将其包含在内。

最后,永远记得加上CUDA error checking .

关于c++ - Cuda中的链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21432714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com