如何从C ++头文件调用CUDA文件? [英] How to call a CUDA file from a C++ header file?

查看:1497
本文介绍了如何从C ++头文件调用CUDA文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道从.c文件调用.cu文件的方法。但现在我想从C头文件调用.cu文件。是可能做到吗?如果是这样,我应该如何使我的项目的设置?请帮助.....

I know the method of calling the .cu files from .c files. But now I want to call the .cu files from a C header file. Is it possible to do it ? If so how should I make the settings of my project ? please help.....

推荐答案

这里有一个工作示例:

file1.h:

int hello();

file2.h:

#include <stdio.h>
#include "file1.h"

int myfunc(){
  hello();
  return 0;
}

file1.cu:

#include <stdio.h>
#include "file1.h"

__global__ void mykernel(){
  printf("Hello from mykernel\n");
}

int hello(){

  mykernel<<<1,1>>>();
  cudaDeviceSynchronize();
  return 0;
}

file2.cpp:

file2.cpp:

#include "file2.h"

int main(){
  myfunc();
  return 0;
}

构建和测试:

$ nvcc -arch=sm_20 -c file1.cu
$ g++ -c file2.cpp
$ g++ -o test file1.o file2.o -L/usr/local/cuda/lib64 -lcudart
$ ./test
Hello from mykernel
$

假设您打算将 file2.h 包含到cpp文件中,您不能直接从该标题调用cuda内核并使用它在cpp文件中。您必须在cuda内核周围放置一个包装,并调用包装器,正如我所指出的。这是因为你的cpp文件将由主机编译器编译,它不知道任何关于cuda语法(例如 mykernel<<<< 1,1>> code>)

Assuming you are intending to include your file2.h into a cpp file, you cannot call a cuda kernel directly from that header and use it in a cpp file. You must put a wrapper around the cuda kernel, and call the wrapper, as I have indicated. This is because your cpp file will get compiled by the host compiler, which doesn't know anything about cuda syntax (e.g. mykernel<<<1,1>>>();)

此外,如注释所示,保留头文件 file2.h 只是为所需的原型,并将 myfunc 的实际函数定义放在一个cpp文件中。

Also, as indicated in the comments, it may make more sense to reserve the header file file2.h just for needed prototypes, and put the actual function definition of myfunc into a cpp file somewhere.

这篇关于如何从C ++头文件调用CUDA文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆