混合编译.c/.cpp与.cu文件
项目中用到cuda编程,写了kernel函数,须要nvcc编译器来编译。.c/.cpp的文件,假定用gcc编译。ios
如何混合编译它们,总体思路是:.cu文件编译出的东西,做为最终编译出的可执行程序的连接依赖。编程
具体提及来又能够有这几种状况:bash
- 分别编译各个文件,最后连接
- 将CUDA程序编译为静态库
- 将CUDA程序弄成动态库
其中后两种方式更工程化,基于makefile或CMake会更加方便。app
假设手头上的文件为:函数
test1.cu test2.c
则具体编译指令、编译脚本以下:优化
方法1:分别编译各个文件
nvcc -c test1.cu gcc -c test2.c gcc -o testc test1.o test2.o -lcudart -L/usr/local/cuda/lib64
方法2: 将cuda程序编译为静态库
nvcc -lib test1.cu -o libtestcu.a gcc test2.c -ltestcu -L. -lcudart -L/usr/local/cuda/lib64
方法3:将CUDA程序弄成动态库
以makefile为例spa
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
方法4:基于CMake的一个例子
foo.cuh
写kernel函数声明 foo.cu
实现kernel函数 foo.cuh
和foo.cu
一块儿,编译成一个库.net
main.c
调用kernel函数debug
foo.cuh
code
参见https://blog.csdn.net/fb_help/article/details/79330815
须要注意的是,VS在debug模式下,应该把nvcc的flags中优化选项关闭掉。
技巧: 能够把kernel函数作一层封装,这样一来在其余.c/.cpp文件中,调用这个wrapper函数便可
e.g.
#include <stdio.h> #include <iostream> #include "foo.cuh" //注意包含头文件 int main() { std::cout<<"Hello C++"<<std::endl; useCUDA(); // 这个函数是kernel函数的wrapper函数 return 0; }