我正在尝试编译和链接 .c 和 .cu 文件,但收到警告
warning: implicit declaration of function
我在 .cu 文件中有一个函数,需要从 .c 文件调用。 .c 文件使用 gcc 编译,.cu 文件使用 nvcc 编译器编译。由于 .cu 文件的头文件包含内置的 cuda 数据类型,我无法将其包含在 .c 文件中。我仍然能够编译和链接所有文件,但我想摆脱我无法做到的警告。代码的基本结构为:
gpu.cu
void fooInsideCuda();
cpu.c
fooInsideCuda(); //calling function in gpu.cu
任何帮助或建议将不胜感激。
最佳答案
此链接:https://devtalk.nvidia.com/default/topic/388072/calling-cuda-functions-from-a-c-file/
回答你的问题:,。基本上:
在.c文件中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cuda.h>
extern void kernel_wrapper(int *a, int *b);
int main(int argc, char *argv[])
{
int a = 2;
int b = 3;
kernel_wrapper(&a, &b);
return 0;
}
并在.cu 文件中;
__global__ void kernel(int *a, int *b)
{
int tx = threadIdx.x;
switch( tx )
{
case 0:
*a = *a + 10;
break;
case 1:
*b = *b + 3;
break;
default:
break;
}
}
void kernel_wrapper(int *a, int *b)
{
int *d_1, *d_2;
dim3 threads( 2, 1 );
dim3 blocks( 1, 1 );
cudaMalloc( (void **)&d_1, sizeof(int) );
cudaMalloc( (void **)&d_2, sizeof(int) );
cudaMemcpy( d_1, a, sizeof(int), cudaMemcpyHostToDevice );
cudaMemcpy( d_2, b, sizeof(int), cudaMemcpyHostToDevice );
kernel<<< blocks, threads >>>( a, b );
cudaMemcpy( a, d_1, sizeof(int), cudaMemcpyDeviceToHost );
cudaMemcpy( b, d_2, sizeof(int), cudaMemcpyDeviceToHost );
cudaFree(d_1);
cudaFree(d_2);
}
然后是一个与此类似的 .h 文件:
#ifndef __B__
#define __B__
#include "cuda.h"
#include "cuda_runtime.h"
extern "C" void kernel_wrapper(int *a, int *b);
#endif
另请注意,.cu 编译器使用 C++ 约定
因此在 .cu 文件中需要类似以下内容:
extern "C" void A(void)
{
.......
}
因此使用“C”约定
关于编译和链接纯 C 和 CUDA 代码 [警告 : implicit declaration of function],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30247592/