Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

c++ - Cmake + CUDA + OpenCV

I have a working C++ project that uses OpenCV. I am creating a CMakeLists.txt file to help people compile it, and everything works fine.

In short : How do I use CMake to create a makefile to compile a ".cu" file into a ".o" with NVCC and link it with the rest of the ".o" files ?

The long version : I want to add a CUDA file that has to be compiled with NVCC. I manage to compile it by hand, but I can't figure out how to use CMake to create a makefile for doing so:

  • Make NVCC compile my .cu file into a .o file if CUDA toolkit is installed, in CMake
  • Use this .o file with the g++ created ones
  • Not use NVCC to compile all the projects (if there is no CUDA support my project can still be compiled)

For now, I have something like this:

IF(CUDA_FOUND)
    MESSAGE( STATUS "I found CUDA !" )
    SET(HAVE_CUDA ${CUDA_FOUND} CACHE BOOL "Set to TRUE if CUDA is found, FALSE otherwise")
    cuda_compile(CudaKernel CudaKernels.cu)
ENDIF(CUDA_FOUND)

This creates a .o file, but I don't know where/how to use it.

I then plan to add a flag like:

if(HAVE_CUDA)
    set (CMAKE_CXX_FLAGS "-DGPU_OPENCV_ENABLE=1")
endif(HAVE_CUDA)

And test that flag in a MACRO in my C++ code to call the good function.

Any idea?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok I figured it out :

We can use Cmake to create an object file for the cuda part and link it to the cpp executable at the end of the compilation.

cmake_minimum_required(VERSION 2.8)
find_package(CUDA REQUIRED)
IF(CUDA_FOUND)
    SET(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-O3 -gencode arch=compute_20,code=sm_20)
    cuda_compile(CudaKernel CudaKernels.cu)
    cuda_add_library(CudaKernels CudaKernels.cu)
    add_definitions(-DGPU_OPENCV_ENABLE)
ENDIF()

And in the Cpp part of the CMake :

target_link_libraries(Executablename
                      CudaKernels
                      libraries...)

Hope it helps someone !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...