如何使用 Cmake link cuda 库到 cpp project/files?

How to link cuda library to cpp project/files with Cmake?

我正在尝试使用 gtk 库编写一个 gui 程序并使用 cuda 库进行一些矩阵运算,但是当我尝试 link 我的项目中的 cuda 库时出现错误。我的 Cmake 看起来像这样:

cmake_minimum_required(VERSION 3.21)
project(untitled1)

set(CMAKE_CXX_STANDARD 14)


find_package(CUDAToolkit)
include_directories(${CUDA_INCLUDE_DIRS})
link_directories(${CUDA_LIBRARY_DIRS})

find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK3 REQUIRED gtk+-3.0)
include_directories(${GTK3_INCLUDE_DIRS})
link_directories(${GTK3_LIBRARY_DIRS})

add_definitions(${GTK3_CFLAGS_OTHER})

add_executable(untitled1 main.cpp bob.h bob.cu)
target_link_libraries(untitled1 ${GTK3_LIBRARIES} ${CUDA_LIBRARIES} ${CUDA_CUDART_LIBRARY})

但是我得到以下错误

-- Unable to find cuda_runtime.h in "/usr/lib/cuda/include" for CUDAToolkit_INCLUDE_DIR.
-- Unable to find cudart library.
-- Could NOT find CUDAToolkit (missing: CUDAToolkit_INCLUDE_DIR CUDA_CUDART) (found version "11.2.67")
-- Configuring done
CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the CMake files:
CUDA_CUDART_LIBRARY (ADVANCED)

我在 Pop OS 21.10 (Ubuntu),我可以在这个项目之外使用 Cuda 库和 nvcc,所以我知道它已经安装并且工作正常。我只是不知道如何 link cuda 库到非 cuda 项目。

编辑:工作CMakeLists.txt thx to dhyun

# Set the minimum version of cmake required to build this project
cmake_minimum_required(VERSION 3.21)

# Set the name and the supported language of the project
project(final CUDA)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CUDA_STANDARD 14)

# Use the package PkgConfig to detect GTK+ headers/library files
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK3 REQUIRED gtk+-3.0)

# Setup CMake to use GTK+, tell the compiler where to look for headers
# and to the linker where to look for libraries
include_directories(${GTK3_INCLUDE_DIRS})
link_directories(${GTK3_LIBRARY_DIRS})

# Add other flags to the compiler
add_definitions(${GTK_CFLAGS_OTHER})

# Add an executable compiled from files:
add_executable(final main.cu showtext.h)

target_link_libraries(final ${GTK3_LIBRARIES})

# Idk what this does or if it's necessary, but it works with it and was there on creation
# So I'm keeping it :)
set_target_properties(final PROPERTIES
        CUDA_SEPARABLE_COMPILATION ON)

我不能说出你的确切设置,但我在 Ubuntu 上通过在项目声明中直接启用 CUDA 作为一种语言而不是使用 find_package(CUDAToolkit) 成功地使用了 CMake 和 CUDA .

像这样:

cmake_minimum_required(VERSION 3.21)
project(untitled1 LANGUAGES CUDA CXX)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CUDA_STANDARD 14)

find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK3 REQUIRED gtk+-3.0)
include_directories(${GTK3_INCLUDE_DIRS})
link_directories(${GTK3_LIBRARY_DIRS})

add_definitions(${GTK3_CFLAGS_OTHER})

add_executable(untitled1 main.cpp bob.h bob.cu)
target_link_libraries(untitled1 ${GTK3_LIBRARIES})

我相信 cudart 是自动链接的,但您需要指定您使用的任何其他库(cufftcublascudnn 等)。