在阅读《GPU高性能运算之CUDA》第26页的matrixAssign例程时,按照书中的代码进行编译时,遇到了点问题。
源文件example_1.cu中的前几行代码如下所示:
#include <stdlib.h> //系统头文件
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <cutil.h> //项目头文件
#include <example_1_kernel.cu> // 核函数,GPU端代码
编译时无法通过,出现如下信息:
error LNK2005: "void __cdecl __device_stub__Z10testKernelPfS_(float *,float *)" 已经在 example_1.cu.obj 中定义
error LNK2005: "void __cdecl testKernel(float *,float *)"已经在 example_1.cu.obj 中定义
fatal error LNK1169: 找到一个或多个多重定义的符号
经过上网一番查询,看到很多网友在学习这个例程时都出现了这个问题,他们分析了原因并给出了解决方案:
原因:example_1.cu中已声明包含了example_1_kernel.cu,在编译example_1.cu时,就已经生成了example_1_kernel.cu中的函数体。如工程中还有example_1_kernel.cu,那么vs会尝试再次编译example_1_kernel.cu,生成的函数体重复了。
解决方案:
方法一:在解决方案资源管理器右键选择example_1_kernel.cu,单击属性,在“从生成中排除”中选择“是”。单击确认,此次生成成功。
方法二:将example_1_kernel.cu的后缀名修改为cuh,并将example_1.cu中前几行代码修改如下:
#include <stdlib.h> //系统头文件
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <cutil.h> //项目头文件
#include “example_1_kernel.cuh”
即可编译成功,运行结果如下图所示: