根据 NVIDIA文档,当 PTX、CUBIN 或 FATBIN 生成时,主机代码会从文件中丢弃。现在我有了我的主机代码 (main.cu) 和设备代码 (shared.cu)。当编译每个文件以*.o
使用 nvcc 选项nvcc -c main.cu shared.cu
,甚至使用选项nvcc -dc main.cu shared.cu
并将它们链接起来时nvcc -link main.o shared.o
,我可以生成可执行文件。但是当shared.cu
编译到shared.cubin
并进一步编译到 时*.o
,链接会失败并出现错误tmpxft_00001253_00000000-4_main.cudafe1.cpp:(.text+0x150): undefined reference to <KERNEL FUNCTION>
我想知道这里shared.cu
只包含设备代码,即使删除了主机代码,为什么链接会失败。
源代码文件是main.cu
#include <stdio.h>
#include <cuda_runtime_api.h>
#include <cuda_runtime.h>
#include <cuda.h>
#include "shared.h"
int main()
{
int a[5]={1,2,3,4,5};
int b[5]={1,1,1,1,1};
int c[5];
int i;
int *dev_a;
int *dev_b;
int *dev_c;
cudaMalloc( (void**)&dev_a, 5*sizeof(int) );
cudaMalloc( (void**)&dev_b, 5*sizeof(int) );
cudaMalloc( (void**)&dev_c, 5*sizeof(int) );
cudaMemcpy(dev_a, a , 5 * sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(dev_b, b , 5 * sizeof(int), cudaMemcpyHostToDevice);
add<<<1,5>>>(dev_a,dev_b,dev_c);
cudaMemcpy(&c,dev_c,5*sizeof(int),cudaMemcpyDeviceToHost);
for(i = 0; i < 5; i++ )
{
printf("a[%d] + b[%d] = %d\n",i,i,c[i]);
}
cudaFree( dev_a);
cudaFree( dev_b);
cudaFree( dev_c);
return 0;
}
共享.cu
#include<stdio.h>
__global__ void add(int *dev_a, int *dev_b, int *dev_c){
//allocate shared memory
__shared__ int a_shared[5];
__shared__ int b_shared[5];
__shared__ int c_shared[5];
{
//get data in shared memory
a_shared[threadIdx.x]=dev_a[threadIdx.x];
__syncthreads();
b_shared[threadIdx.x]=dev_b[threadIdx.x];
__syncthreads();
//perform the addition in the shared memory space
c_shared[threadIdx.x]= a_shared[threadIdx.x] + b_shared[threadIdx.x];
__syncthreads();
//shift data back to global memory
dev_c[threadIdx.x]=c_shared[threadIdx.x];
__syncthreads();
}
}
共享.h
#ifndef header
#define header
extern __global__ void add(int *dev_a, int *dev_b, int *dev_c);
#endif