CMake: how to add cuda to existing project

2019-03-10 04:17发布

I have a project that builds a library and I want to add some cuda support to it.

The structure is:

|Basedir
|_subdir1
|_subdir2

The basic structure of the CMakeLists.txt files: (subdir2 is not important).
in Basedir:

cmake_minimum_required(VERSION 2.6)
PROJECT(myproject)
find_package(CUDA)
INCLUDE_DIRECTORIES(${MYPROJECT_SOURCE_DIR})
ADD_SUBDIRECTORY(subdir1)
ADD_SUBDIRECTORY(subdir2)

in subdir1:

ADD_LIBRARY(mylib shared
    file1.cpp
    file2.cpp
    file3.cpp
)

INSTALL(
TARGETS mylib
DESTINATION lib
PERMISSIONS
    OWNER_READ OWNER_WRITE OWNER_EXECUTE
    GROUP_READ GROUP_EXECUTE
    WORLD_READ WORLD_EXECUTE
)

FILE(GLOB_RECURSE HEADERS RELATIVE ${MYPROJECT_SOURCE_DIR}/myproject *.h)

FOREACH(HEADER ${HEADERS})
    STRING(REGEX MATCH "(.*)[/\\]" DIR ${HEADER})
    INSTALL(FILES ${HEADER} DESTINATION include/myproject/${DIR})
ENDFOREACH(HEADER)

I actually don't really know how to put the cuda-support into it. I want to replace file2.cpp with file2.cu and I did that, but it didn't build the .cu file, only the cpp files.

Do I have to add CUDA_ADD_EXECUTABLE() to include any cuda-files? How will I then link it to the other files?

I tried adding the following to the CMakeLists.txt in subdir1:

CUDA_ADD_EXECUTABLE(cuda file2.cu OPTIONS -arch sm_20)

That will compile the file but build an executable cuda. How do I link it to mylib? Just with?:

TARGET_LINK_LIBRARIES(cuda mylib)

I have to admit that I'm not experienced in cmake, but I guess you figured that.

标签: cuda cmake
1条回答
何必那么认真
2楼-- · 2019-03-10 04:50

You can use CUDA_ADD_LIBRARY for mylib project. It works as CUDA_ADD_EXECUTABLE but for libraries.

CUDA_ADD_LIBRARY(mylib SHARED
    file1.cpp
    file2.cu
    file3.cpp
    OPTIONS -arch sm_20
)

TARGET_LINK_LIBRARIES(mylib ${CUDA_LIBRARIES})
查看更多
登录 后发表回答