如何使用 CMake 将 C++ 编译为 CUDA [英] How to compile C++ as CUDA using CMake

查看:56
本文介绍了如何使用 CMake 将 C++ 编译为 CUDA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些可以编译为 C++ 或 CUDA 的代码.在后一种情况下,它使用 CUDA 内核,在前一种情况下,它只运行常规代码.

I'm writing some code that can be compiled as C++ or as CUDA. In the latter case, it makes use of CUDA kernels, in the former it just runs conventional code.

创建了一个名为 test.cpp 的文件后,我可以手动编译它:

Having created a file named test.cpp, I can compile it manually thus:

g++ test.cpp          # build as C++ with GCC
nvcc -x cu test.cpp   # build as CUDA with NVCC

where -x cu 告诉 nvcc 虽然它是一个 .cpp 扩展名,但我希望它把它当作 CUDA.到目前为止,一切都很好.

where -x cu tells nvcc that although it's a .cpp extension, I'd like it to treat it as CUDA. So far, so good.

然而,当我迁移到使用 CMake 时,我不知道如何做同样的事情.即:如何让CMake用NVCC而不是GCC编译.cpp文件.

However, when I migrate to using CMake, I don't know how to do the same thing. That is: how to ask CMake to compile the .cpp file with NVCC, rather than GCC.

cmake_minimum_required(VERSION 3.9)
project(cuda_test LANGUAGES CUDA CXX)
add_executable(cuda_test test.cpp)     # builds with GCC

如果我创建一个指向原始文件的符号链接:

If I create a symlink to the original file:

ln -s test.cpp test.cu

然后更改 CMakeLists.txt:

then change CMakeLists.txt:

add_executable(cuda_test test.cu)     # builds with NVCC

但我希望能够在 CMake 中指定等效于 NVCC 的 -x 开关,而不是玩带有扩展的游戏.类似:

But I'd like to be able to specify the equivalent of NVCC's -x switch within CMake, rather than playing games with extensions. Something like:

set_target_properties(cuda_test PROPERTIES FORCE_LANGUAGE CUDA)

甚至

set_target_properties(test.cpp PROPERTIES FORCE_LANGUAGE CUDA)

这种咒语存在吗?

推荐答案

默认情况下,CMake 会根据文件的扩展名为源文件选择编译器.但是您可以通过设置 LANGUAGE 文件的属性:

By default, CMake chooses compiler for a source file according to the file's extension. But you may force CMake to use the compiler you want by setting LANGUAGE property for a file:

set_source_files_properties(test.cpp PROPERTIES LANGUAGE CUDA)

(这只是使用普通编译器选项为文件调用 CUDA 编译器.您仍然需要为该编译器传递其他选项,以便它可以使用不寻常的文件扩展名.)

(This just calls CUDA compiler for a file using normal compiler options. You still need to pass additional options for that compiler, so it could work with the unusual file's extension.)

这篇关于如何使用 CMake 将 C++ 编译为 CUDA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆