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

查看:406
本文介绍了如何使用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

作为CUDA构建,其中 -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 来强制CMake使用所需的编译器。 a>文件属性:

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天全站免登陆