268 字
1 分钟
CUDA和C/C++混编
2024-08-12

CUDA和C/C++混编#

1、编译方式#

项目中用到cuda编程,写了kernel函数,需要nvcc编译器来编译。.c/.cpp的文件,假定用gcc编译。

如何混合编译它们,整体思路是:.cu文件编译出的东西,作为最终编译出的可执行程序的链接依赖。

具体说起来又可以有这几种情况:

  • 分别编译各个文件,最后链接
  • 将CUDA程序编译为静态库
  • 将CUDA程序弄成动态库

其中后两种方式更工程化,基于makefile或CMake会更加方便。

假设手头上的文件为:

test1.cu
test2.c

则具体编译指令、编译脚本如下:

**方法1:**分别编译各个文件

Terminal window
$ nvcc -c test1.cu
$ gcc -c test2.c
$ gcc -o testc test1.o test2.o -lcudart -L/usr/local/cuda/lib64

**方法2:**将cuda程序编译为静态库

Terminal window
$ nvcc -lib test1.cu -o libtestcu.a
$ gcc test2.c -ltestcu -L. -lcudart -L/usr/local/cuda/lib64

**方法3:**将cuda程序编译为动态库 以makefile为例

$ all: c
$ c: libtestcu.so
$ gcc test2.c -ltestcu -L. -lcudart -L/usr/local/cuda/lib64 -o testc
$ libtestcu.so: test.cu
$ nvcc -o libtestcu.so -shared -Xcompiler -fPIC test1.cu

Reference#

【1】 https://www.cnblogs.com/zjutzz/p/10272424.html

【2】NVIDIA CUDA Compiler Driver

CUDA和C/C++混编
https://tuoyuangui.github.io/website/posts/typora/cuda/cuda混编/
作者
椭圆规/tuoyuangui
发布于
2024-08-12
许可协议
CC BY-NC-SA 4.0