Cmake + CUDA + OpenCV

2019-05-26 11:16发布

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?

1条回答
手持菜刀,她持情操
2楼-- · 2019-05-26 11:56

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 !

查看更多
登录 后发表回答