我正在尝试编译和链接.c和.cu文件,但收到警告

 warning: implicit declaration of function


我需要从.c文件调用的.cu文件中有一个函数。 .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”约定

10-08 07:11
查看更多