435 字
2 分钟
混合编译.c/.cpp与.cu文件
混合编译.c/.cpp与.cu文件
项目中用到cuda编程,写了kernel函数,需要nvcc编译器来编译。.c/.cpp的文件,假定用gcc编译。
如何混合编译它们,整体思路是:.cu文件编译出的东西,作为最终编译出的可执行程序的链接依赖。
具体说起来又可以有这几种情况:
- 分别编译各个文件,最后链接
- 将CUDA程序编译为静态库
- 将CUDA程序弄成动态库
其中后两种方式更工程化,基于makefile或CMake会更加方便。
假设手头上的文件为:
test1.cutest2.c则具体编译指令、编译脚本如下:
方法1:分别编译各个文件
nvcc -c test1.cugcc -c test2.cgcc -o testc test1.o test2.o -lcudart -L/usr/local/cuda/lib64方法2: 将cuda程序编译为静态库
nvcc -lib test1.cu -o libtestcu.agcc 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方法4:混合编译.c/.cpp与.cu文件
先分别编译,再联合, 编译动态库需要把环境变量$LD_LIBRARY_PATH进行修改,否则无法成功
CC=/usr/bin/gccNVCC=/usr/local/cuda-11.8/bin/nvccLIB=/usr/local/cuda-11.8/lib64INC=/usr/local/cuda-11.8/includeCFLAGS=-I$(INC) -L$(LIB) -lcudart -lstdc++ -lcuda
SRCCS=$(wildcard *.c) # .c src fileSRCUS=$(wildcard *.cu) # .cu src file
# cOBJCCS_static =$(patsubst %.c, %.o, $(SRCCS))OBJCCS_dynamic=$(patsubst %.c, %.os, $(SRCCS))# cuOBJCUS_static =$(patsubst %.cu, %.o, $(SRCUS))OBJCUS_dynamic=$(patsubst %.cu, %.os, $(SRCUS))
%.os:%.c $(CC) -o $@ -c -O3 -fPIC -shared -Wall $<%.o:%.c $(CC) -o $@ -c -O3 -Wall -lm $<
%.os:%.cu $(NVCC) -o $@ -c -Xcompiler -fPIC --use_fast_math -O3 $<%.o:%.cu $(NVCC) -o $@ -c -O3 -lcudart --use_fast_math $<
install_dynamic:$(OBJCUS_dynamic) $(OBJCCS_dynamic) $(CC) -o libdlglcu.so $^ -fPIC -shared -lm $(CFLAGS)
install_static:$(OBJCUS_static) $(OBJCCS_static) ar rc liblglcu.a $^ ranlib liblglcu.a
header: paste *.h *.cuh -s > lglcu.h
install: install_dynamic install_static header
clean: -rm -rf *.o *.os lglcu.h liblglcu.a libdlglcu.soreference:
【1】https://www.cnblogs.com/zjutzz/p/10272424.html
【2】https://blog.csdn.net/bruce_0712/article/details/78515133
混合编译.c/.cpp与.cu文件
https://tuoyuangui.github.io/website/posts/typora/cuda/nvcc动态静态库编译/