在Microsoft Windows上开始使用OpenCL

Getting started with OpenCL on Microsoft Windows

在Microsoft Windows上开始使用OpenCL

OpenCL is not native to the Windows operating system, and as such isn't supported across the board of UWP (Universal Windows Platform) platforms (XBox, Hololens, IoT, PC) and the Microsoft Store. Windows as a traditional content creating platform however can build and execute OpenCL applications when built as traditional Win32 GUI or console applications.

OpenCL不是Windows操作系统的原生版本,因此不支持UWP(通用Windows平台)平台(XBox、Hololens、IoT、PC)和Microsoft Store。然而,Windows作为传统的内容创建平台,当作为传统的Win32 GUI或控制台应用程序构建时,可以构建和执行OpenCL应用程序。

(NOTE: Nothing prevents from using advanced WinRT capabilities to use the ICD in packaged applications (APPX/MSIX), however such applications will most certainly not be able to load a functioning OpenCL runtime on platforms other than PC and a few IoT devices.)

(注意:没有什么可以阻止在打包应用程序(APPX/MSIX)中使用高级WinRT功能来使用ICD,但这些应用程序肯定无法在PC和一些物联网设备以外的平台上加载正常运行的OpenCL运行时。)

In this guide we're minimally going to use the following tools:

在本指南中,我们将最低限度地使用以下工具:

  • The command-line
  • 命令行
  • C/C++ compiler
  • C/C++编译器

And depending on which ways one extends the bare minimum:

根据扩展最低限度的方式:

  • CMake (Cross-platform Make)
  • CMake(跨平台Make)
  • Git
  • Vcpkg (Cross-platform pacakge management)
  • Vcpkg(跨平台包装管理)
  • Visual Studio Code
  • Visual Studio代码

Steps will be provided to obtain a minimal and productive environment.

将采取步骤,以获得最低限度的生产环境。

Installation

安装

In this guide we'll be using latest (at the time of writing) Windows 10. Installation for the most part will happen via winget, the 1st party command-line tool for installing software on Windows. If for whatever reason you do not have the winget client on your PATH, it is bundled with the App Installer package in the Microsoft Store. Updating this component should also install the command-line tool.

​在本指南中,我们将使用最新的(在撰写本文时)Windows 10。大部分安装将通过winget进行,winget是在Windows上安装软件的第一方命令行工具。无论出于何种原因,如果您的PATH上没有winget客户端,它将与Microsoft商店中的应用程序安装程序包捆绑在一起。更新此组件还应安装命令行工具。

(NOTE: installation commands if not issued from a shell with Administrator privileges, UAC prompts will pop up. If you are in an automated scenario where that's an issue, make sure to work in such a shell.)

(注意:如果安装命令不是从具有管理员权限的shell发出的,则会弹出UAC提示。如果您处于出现问题的自动化场景中,请确保在这样的shell中工作。)

After installing everything, open a new shell, otherwise the tools will not be available on the PATH for convenient invocation.

安装完所有内容后,请打开一个新的shell,否则工具将无法在PATH上进行方便的调用。

C/C++ compiler

C/C++编译器

Open your favorite shell in your favorite terminal and issue:

在您喜爱的终端中打开您喜爱的shell,然后发出:

winget install "Visual Studio Build Tools 2022"
Command-line component selection
命令行组件选择

In automated scenarios with no GUI available, please consult the VS docs on specifying the required workloads. A minimal configuration which may be imported using the GUI or specfied on the command-line is as:

​在没有GUI可用的自动化场景中,请参阅VS文档以指定所需的工作负载。可以使用GUI导入或在命令行上指定的最小配置如下:

& "C:\Program Files (x86)\Microsoft Visual Studio\Installer\setup.exe" install --passive --norestart --productId Microsoft.VisualStudio.Product.BuildTools --channelId VisualStudio.17.Release --add Microsoft.VisualStudio.Component.VC.Tools.x86.x64 --add Microsoft.VisualStudio.Component.VC.Redist.14.Latest

Developers targeting Windows 10 will need to add --add Microsoft.VisualStudio.Component.Windows10SDK.19041 to the command-line while targeting Windows 11 requires --add Microsoft.VisualStudio.Component.Windows11SDK.22000

针对Windows 10的开发人员需要向命令行添加--add Microsoft.VisualStudio.Component.Windows10SDK.19041,而针对Windows 11的开发人员则需要--添加Microsoft.VisualStudio Component.Windows11SDK.22000

Git

You most likely already have Git installed. If not, we'll install it, because this is what Vcpkg uses to keep it's repository up-to-date. Open your favorite shell in your faovrite terminal and issue:

你很可能已经安装了Git。如果没有,我们将安装它,因为这是Vcpkg用来保持其存储库最新的功能。在你的faovrite终端中打开你最喜欢的shell并发布:

winget install Git.Git

CMake

If you do not have CMake installed yet, we'll install it, as it's the primary supported build system, as it will make our builds much simpler. Open your favorite shell in your faovrite terminal and issue:

如果您还没有安装CMake,我们将安装它,因为它是主要支持的构建系统,因为它将使我们的构建更加简单。在你的faovrite终端中打开你最喜欢的shell并发布:

winget install Kitware.CMake

Visual Studio Code

While IDEs are highly opinionated, for an IDE with widespread adoption and small footprint, VS Code has everything (and more) to get off the ground.

虽然IDE非常固执己见,但对于一个广泛采用且占地面积小的IDE来说,VS Code有一切(甚至更多)需要起步。

winget install "Visual Studio Code" --source msstore

OpenCL-SDK

To build native OpenCL applications, one will minimally need:

要构建本机OpenCL应用程序,最低限度地需要:

  • C or C++ compiler
  • C或C++编译器
  • The OpenCL headers
  • OpenCL头文件
    • The C and optionally the C++ headers
    • C和可选的C++头文件
  • An Installable Client Driver (ICD) Loader
  • 可安装客户端驱动程序(ICD)加载器
    • Dynamic library (OpenCL.dll)
    • 动态库(OpenCL.dll)
    • Export library (OpenCL.lib)
    • 导出库(OpenCL.lib)

The SDK can be installed from a package manager like Vcpkg or can be built on-demand from their canonical repositories.

SDK可以从像Vcpkg这样的包管理器中安装,也可以从它们的规范存储库中按需构建。

GitHub

If you want to build an SDK from source, the recommended way is cloning the OpenCL-SDK repo.

如果你想从源代码构建SDK,建议的方法是克隆OpenCL SDK repo。

git clone --recursive https://github.com/KhronosGroup/OpenCL-SDK.git
cmake -G "Visual Studio 17 2022" -A x64 -T v143 -D CMAKE_INSTALL_PREFIX=./OpenCL-SDK/install -B ./OpenCL-SDK/build -S ./OpenCL-SDK
cmake --build OpenCL-SDK/build --config Release --target install -- /m /v:minimal

Vcpkg

Compiling on the command-line

在命令行上编译

On Windows the default system command interpreter is cmd.exe. (This is analogous to /bin/sh in Linux.) The default shell however is PowerShell which provides better user-experience overall. (Much like Linux defaults to /bin/bash.) PowerShell provides a better CLI experience overall.

在Windows上,默认的系统命令解释器是cmd.exe。(这类似于Linux中的/bin/sh。)然而,默认的shell是PowerShell,它总体上提供了更好的用户体验。(与Linux默认值/bin/bash非常相似。)PowerShell总体上提供了更好的CLI体验。

Invoking the compiler manually

手动调用编译器

Unlike compilers native to *nix OS flavors, MSVC relies on a few environmental variables to function properly. Such environments are referred to as Developer Command Prompt or Developer PowerShell, which are nothing more than ordinary shells with these environmental variables setup.)

与*nix OS风格的原生编译器不同,MSVC依赖于一些环境变量才能正常工作。这样的环境被称为Developer Command Prompt或Developer PowerShell,它们只不过是设置了这些环境变量的普通shell。)

Developer Command Prompt
开发人员命令提示符

To build applications on the command-line using cmd.exe on Windows, one needs to open a Developer Command Prompt for VS 2022. This can be done in the Start Menu or by invoking vcvarsall.bat from the installation folder.

要在Windows上使用cmd.exe在命令行上构建应用程序,需要打开VS 2022的开发人员命令提示符。这可以在「开始」菜单中完成,也可以从安装文件夹中调用vcvarsall.bat。

"C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvarsall.bat" amd64

(Note: for all combinations of available host-target toolset variables, consult vcvarsall.bat help)

(注意:有关可用主机目标工具集变量的所有组合,请参阅vcvarsall.bat帮助)

Developer PowerShell
开发人员PowerShell

Inheriting environments set up by batch scripts is not trivial, hence VS provides a PowerShell module doing the same thing. The module is inside an assembly shipping with VS. To have the utility available in all shells, invoke the following from PowerShell:

继承批处理脚本设置的环境并非易事,因此VS提供了一个PowerShell模块来做同样的事情。该模块位于与VS一起提供的程序集中。若要使该实用程序在所有外壳程序中都可用,请从PowerShell调用以下命令:

if (-not (Test-Path ~\Documents\PowerShell)) { New-Item -Type Directory ~\Documents\PowerShell }
'Import-Module "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"' >> $PROFILE
function devshell { Enter-VsDevShell -InstallPath "C:\Kellekek\Microsoft\VisualStudio\2019\BuildTools" -SkipAutomaticLocation -DevCmdArguments "-arch=x64 -no_logo" }

Opening a new shell, one now can enter a Developer PowerShell by issuing:

打开一个新的shell,现在可以通过发出以下命令进入Developer PowerShell:

devshell -VsInstallPath 'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\' -DevCmdArguments '-arch=x64 -no_logo'

Inside a Developer Command Prompt navigate to the folder where you wish to build your application. Our application will have a single Main.c source file:

在开发人员命令提示符中导航到要构建应用程序的文件夹。我们的应用程序将有一个Main.c源文件:

// C standard includes
#include <stdio.h>

// OpenCL includes
#include <CL/cl.h>

int main()
{
    cl_int CL_err = CL_SUCCESS;
    cl_uint numPlatforms = 0;

    CL_err = clGetPlatformIDs( 0, NULL, &numPlatforms );

    if (CL_err == CL_SUCCESS)
        printf_s("%u platform(s) found\n", numPlatforms);
    else
        printf_s("clGetPlatformIDs(%i)\n", CL_err);

    return 0;
}

Then invoke the compiler to build our source file as such:

然后调用编译器来构建我们的源文件,如下所示:

GitHub

cl.exe /nologo /TC /W4 /DCL_TARGET_OPENCL_VERSION=100 /I<SDKINSTALLROOT>\include\ Main.c /Fe:HelloOpenCL /link /LIBPATH:<SDKINSTALLROOT>\lib OpenCL.lib

Vcpkg

What do the command-line arguments mean?

命令行参数是什么意思?

  • /nologo makes the compiler omit printing a banner to the console
  • /nologo使编译器省略了向控制台打印横幅
  • /TC tells it to treat all source files as C
  • /TC告诉将所有源文件视为C
  • /W4 turns on Warning level 4 (highest sensible level)
  • /W4打开警告级别4(最高可感知级别)
  • /D instructs the preprocessor to create a define with NAME:VALUE
  • /D指示预处理器使用NAME:VALUE创建一个定义
    • CL_TARGET_OPENCL_VERSION enables/disables API functions corresponding to the defined version. Setting it to 100 will disable all API functions in the header that are newer than OpenCL 1.0
    • CL_TARGET_OPENCL_VERSION启用/禁用对应于定义版本的API函数。将其设置为100将禁用头中比OpenCL 1.0更新的所有API函数
  • /I sets additional paths to the include directory search paths
  • /I 将其他路径设置为包含目录搜索路径
  • Main.c is the name of the input source file
  • Main.c是输入源文件的名称
  • /Fe: sets the name of the output executable (default would be Main.exe)
  • /Fe:设置输出可执行文件的名称(默认为Main.exe)
  • /link allows passing arguments to the linker invoked by the compiler driver (flags of the compiler should not follow this argument)
  • /link 允许将参数传递给编译器驱动程序调用的链接器(编译器的标志不应跟在该参数后面)
  • /LIBPATH sets additional paths to the library directory search paths
  • /LIBPATH为库目录搜索路径设置其他路径
  • OpenCL.lib is the vendor neutral ICD loader to link to
  • OpenCL.lib是与供应商无关的ICD加载程序,可链接到

Running our executable HelloOpenCL.exe either prints the number of platforms found or an error code which is often the result of corrupted runtime installations.

运行我们的可执行文件HelloOpenCL.exe会打印找到的平台数量或错误代码,这通常是运行时安装损坏的结果。

Automating the build using CMake

使用CMake实现构建自动化

The CMake build script for this application that builds it as an ISO C11 app with most sensible compiler warnings turned on looks like:

该应用程序的CMake构建脚本将其构建为ISO C11应用程序,并打开了最合理的编译器警告,其外观如下:

cmake_minimum_required(VERSION 3.1) # 3.1 << C_STANDARD 11

project(HelloOpenCL LANGUAGES C)

find_package(OpenCL CONFIG REQUIRED)

add_executable(${PROJECT_NAME} Main.c)

target_link_libraries(${PROJECT_NAME} PRIVATE OpenCL::OpenCL)

set_target_properties(${PROJECT_NAME} PROPERTIES C_STANDARD 11
                                                 C_STANDARD_REQUIRED ON
                                                 C_EXTENSIONS OFF)

target_compile_definitions(${PROJECT_NAME} PRIVATE CL_TARGET_OPENCL_VERSION=100)

What does the script do?

这个脚本是做什么的?

  • Give a name to the project and tell CMake to only look for a C compiler (default is to search for a C and a C++ compiler)
  • 为项目命名,并告诉CMake只查找C编译器(默认情况下搜索C和C++编译器)
  • Look for an OpenCL SDK and fail if not found
  • 查找OpenCL SDK,如果找不到则失败
    • If detection fails, refer to the CMake Build-System Support chapter.
    • ​如果检测失败,请参阅CMake Build System Support一章。
  • Specify our source files and name the executable
  • 指定我们的源文件并命名可执行文件
  • Specify dependency to the SDK (not just linkage)
  • 指定对SDK的依赖关系(不仅仅是链接)
  • Set language properties to all source files of our application
  • 为应用程序的所有源文件设置语言属性
  • Set the OpenCL version target to control API coverage in header
  • 设置OpenCL版本目标以控制标头中的API覆盖范围
  • Because CMake cannot handle warning levels portably, set compiler specific flags. Guard it with a generator expression (terse conditionals), so other compilers will not pick up such non-portable flags.
  • 由于CMake无法便携地处理警告级别,请设置编译器特定的标志。用生成器表达式(简洁的条件)保护它,这样其他编译器就不会获取这种不可移植的标志。

To invoke this script, place it next to our Main.c file in a file called CMakeLists.txt. Once that's done, cmake may be invoked the following way to generate Ninja makefiles in the advised out-of-source fashion into a subfolder named build:

要调用此脚本,请将其放在名为CMakeLists.txt的文件中的Main.c文件旁边。完成后,可以通过以下方式调用cmake,以建议的源代码外方式将Ninja makefile生成到名为build的子文件夹中:

GitHub

cmake -A x64 -S . -B .\build -D CMAKE_PREFIX_PATH=<SDKINSTALLROOT>

Vcpkg

Which will output something like

它将输出以下内容

-- The C compiler identification is MSVC 19.22.27905.0
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio620226BuildTools/VC/Tools/MSVC/14.22.27905/bin/Hostx64/x64/cl.exe
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio620226BuildTools/VC/Tools/MSVC/14.22.27905/bin/Hostx64/x64/cl.exe -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Looking for CL_VERSION_2_2
-- Looking for CL_VERSION_2_2 - found
-- Found OpenCL: C:/Users/mnagy/Source/Repos/vcpkg/installed/x64-windows/debug/lib/OpenCL.lib (found version "2.2")
-- Looking for pthread.h
-- Looking for pthread.h - not found
-- Found Threads: TRUE
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/mnagy/Source/CL-Min1/build

To kick off the build, one may use CMakes build driver:

要启动构建,可以使用CMakes构建驱动程序:

cmake --build .\build --config Release

Once build is complete, we can run it by typing:

构建完成后,我们可以通过键入以下内容来运行它:

.\build\Release\HelloOpenCL.exe
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值