The Complete Guide to OpenCL Programming in C
Learn OpenCL 3.0 in C from platform discovery to kernels, buffers, work-groups, local memory, events and profiling, with complete programs and their output.

OpenCL is the Khronos Group standard for running computations on GPUs, CPUs and other accelerators from one source, and it is the other major route into general-purpose GPU programming besides CUDA. Where CUDA is a language and toolchain for NVIDIA hardware, OpenCL is a specification: a C host API that discovers devices, builds kernels at run time and queues work, and a C-based kernel language for the device code. The same program can run on an NVIDIA, AMD or Intel GPU, on a CPU through a software implementation, and on some FPGAs and embedded accelerators, provided a vendor driver exists. This guide teaches OpenCL 3.0 from the first call to a profiled, multi-kernel program, in C, with complete examples whose output we work out from the code. If you know CUDA, you will recognize every concept under a different name, and the guide shows the mapping. The decision about whether OpenCL is the right choice for your project is in the CUDA, OpenCL and Vulkan comparison. The authoritative sources are the Khronos OpenCL 3.0 specification and the OpenCL C 3.0 specification, which we cite throughout.
The platform model
OpenCL describes a machine as a hierarchy, and the API follows it object by object.
A platform is one vendor's OpenCL implementation installed on the machine. A machine with an NVIDIA driver and an Intel driver has two platforms. A device belongs to a platform and is something that can run kernels, such as a GPU or a CPU. A context groups one or more devices of one platform and owns the memory objects and programs you create. A command queue belongs to one device inside a context and is where you submit work: kernel launches and memory transfers. A program is OpenCL C source or a compiled binary, and a kernel is one function from a built program that you can launch. A buffer is a block of device-accessible memory.
Execution follows a model with two levels. When you enqueue a kernel, you specify an NDRange, an index space of one, two or three dimensions. Each point in that space is a work-item, one running instance of the kernel. Work-items are grouped into work-groups, and the work-items in one group can share fast local memory and synchronize with a barrier, while work-items in different groups cannot. The sizes are your choice: the total number of work-items is the global size, and the work-group shape is the local size.
The mapping to CUDA terms is direct, and worth keeping in front of you:
| OpenCL | CUDA | Notes |
|---|---|---|
| Work-item | Thread | One instance of the kernel |
| Work-group | Thread block | Shares local memory, can barrier |
| NDRange global size | Grid size times block size | OpenCL states total work-items, CUDA states blocks |
get_global_id(0) | blockIdx.x * blockDim.x + threadIdx.x | |
get_local_id(0) | threadIdx.x | |
get_group_id(0) | blockIdx.x | |
get_local_size(0) | blockDim.x | |
__local memory | __shared__ memory | |
barrier(CLK_LOCAL_MEM_FENCE) | __syncthreads() | |
| Command queue | Stream | |
| Event | Event |
One difference trips up CUDA programmers at once: in CUDA you state the number of blocks and the threads per block, and the total is their product. In OpenCL you state the total and the group size, so the total is a multiple of the group size unless your device supports non-uniform work-groups.
OpenCL versions and what 3.0 changed
The specification went through 1.0, 1.1, 1.2, 2.0, 2.1, 2.2 and 3.0. Vendors adopted 2.x unevenly, and some never moved past 1.2. OpenCL 3.0, released in 2020, resolved the split by making 1.2 the mandatory baseline and turning most 2.x features, including shared virtual memory, pipes and generic address spaces, into optional features that a driver reports through queries. The consequence for you is that portable code targets the 1.2 feature set plus whatever it checks for at run time. You select the API version your code expects with a macro before including the header:
#define CL_TARGET_OPENCL_VERSION 300
#include <CL/cl.h>Without the macro, headers from recent SDKs print a warning about the default target version. Build with gcc program.c -o program -lOpenCL, linking the ICD loader, a small library that finds installed vendor drivers through files in the system's ICD directory and forwards calls to the right one. If the loader finds no driver, clGetPlatformIDs returns zero platforms, and the tool clinfo is the quickest way to see what is installed:
clinfo | head -n 12Number of platforms 1
Platform Name Example Vendor OpenCL
Platform Vendor Example Vendor
Platform Version OpenCL 3.0
Platform Profile FULL_PROFILE
Platform Extensions cl_khr_icd cl_khr_...
Platform Name Example Vendor OpenCL
Number of devices 1
Device Name Example GPU
Device Vendor Example Vendor
Device Version OpenCL 3.0
Driver Version 550.00The values shown are placeholders, since they depend on your hardware and driver.
Your first complete program: vector addition
The program below adds two vectors on the first GPU it finds. It is long, because OpenCL asks you to do explicitly what CUDA's runtime does behind the scenes, and every part of it is explained after the listing.
#define CL_TARGET_OPENCL_VERSION 300
#include <CL/cl.h>
#include <stdio.h>
#include <stdlib.h>
#define CHECK(err, what) do { if ((err) != CL_SUCCESS) { \
fprintf(stderr, "%s failed: %d\n", what, (int)(err)); exit(1); } } while (0)
static const char *source =
"__kernel void vadd(__global const float *a,\n"
" __global const float *b,\n"
" __global float *c,\n"
" const int n)\n"
"{\n"
" int i = get_global_id(0);\n"
" if (i < n) c[i] = a[i] + b[i];\n"
"}\n";
int main(void)
{
cl_int err;
const int n = 8;
float a[8], b[8], c[8];
for (int i = 0; i < n; ++i) { a[i] = (float)i; b[i] = 10.0f * i; }
cl_platform_id platform;
err = clGetPlatformIDs(1, &platform, NULL);
CHECK(err, "clGetPlatformIDs");
cl_device_id device;
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);
CHECK(err, "clGetDeviceIDs");
cl_context ctx = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
CHECK(err, "clCreateContext");
cl_command_queue queue = clCreateCommandQueueWithProperties(ctx, device, NULL, &err);
CHECK(err, "clCreateCommandQueueWithProperties");
cl_program program = clCreateProgramWithSource(ctx, 1, &source, NULL, &err);
CHECK(err, "clCreateProgramWithSource");
err = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
CHECK(err, "clBuildProgram");
cl_kernel kernel = clCreateKernel(program, "vadd", &err);
CHECK(err, "clCreateKernel");
cl_mem dA = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(a), a, &err);
cl_mem dB = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(b), b, &err);
cl_mem dC = clCreateBuffer(ctx, CL_MEM_WRITE_ONLY, sizeof(c), NULL, &err);
CHECK(err, "clCreateBuffer");
clSetKernelArg(kernel, 0, sizeof(cl_mem), &dA);
clSetKernelArg(kernel, 1, sizeof(cl_mem), &dB);
clSetKernelArg(kernel, 2, sizeof(cl_mem), &dC);
clSetKernelArg(kernel, 3, sizeof(int), &n);
size_t global = n;
err = clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &global, NULL, 0, NULL, NULL);
CHECK(err, "clEnqueueNDRangeKernel");
err = clEnqueueReadBuffer(queue, dC, CL_TRUE, 0, sizeof(c), c, 0, NULL, NULL);
CHECK(err, "clEnqueueReadBuffer");
for (int i = 0; i < n; ++i) printf("%.0f ", c[i]);
printf("\n");
clReleaseMemObject(dA); clReleaseMemObject(dB); clReleaseMemObject(dC);
clReleaseKernel(kernel); clReleaseProgram(program);
clReleaseCommandQueue(queue); clReleaseContext(ctx);
return 0;
}0 11 22 33 44 55 66 77Each output is i + 10 * i, so 11 times i. The kernel source is a C string compiled at run time by the driver, which is the biggest structural difference from CUDA: there is no separate compile step in your build. The call sequence is the same in nearly every OpenCL program, and it is worth learning it in order.
clGetPlatformIDs and clGetDeviceIDs find a device, here the first GPU of the first platform. A real program loops over platforms and devices and chooses by a rule, such as device type, name or memory size. clCreateContext takes the device list and returns a context. clCreateCommandQueueWithProperties is the OpenCL 2.0 and later function that creates a queue, and it replaces the deprecated clCreateCommandQueue; passing NULL for the properties gives an in-order queue with no profiling. clCreateProgramWithSource wraps the source string, and clBuildProgram compiles it for the listed devices. clCreateKernel extracts one function by name.
Buffers come from clCreateBuffer. The flags describe access from the device's point of view and the initial data: CL_MEM_READ_ONLY and CL_MEM_WRITE_ONLY tell the runtime how the kernel uses the buffer, and CL_MEM_COPY_HOST_PTR copies the host array into the new buffer at creation. Arguments are set one at a time with clSetKernelArg, passing the argument index, the size and a pointer to the value. For a buffer, the size is sizeof(cl_mem) and the value is the handle, not the data. A wrong size or a wrong index for a scalar argument is a common mistake, and the error appears at enqueue time as CL_INVALID_KERNEL_ARGS.
clEnqueueNDRangeKernel launches the kernel on a one-dimensional index space of 8 work-items. Passing NULL for the local size lets the implementation choose the work-group size. The read at the end is blocking, CL_TRUE, so the call returns after the kernel has finished and the data has arrived. Because the queue is in-order, the read waits for the kernel without an explicit dependency.
Check errors, and read the build log
Every OpenCL call returns an error code, either directly or through the last parameter. Treat them like the CUDA runtime's: check each one. The macro in the example is a minimum. The error you will meet first is a failed build, because the kernel is compiled at run time and your first typos in OpenCL C appear then, as CL_BUILD_PROGRAM_FAILURE, numeric value -11. The reason is in the build log, which you must request explicitly:
if (err == CL_BUILD_PROGRAM_FAILURE) {
size_t logSize = 0;
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);
char *log = malloc(logSize);
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, logSize, log, NULL);
fprintf(stderr, "build log:\n%s\n", log);
free(log);
}The call pattern, ask for the size first with a null buffer and then allocate and ask again, appears all over the API. For a kernel with a missing semicolon, the log contains a compiler message with the line number inside the kernel string, and the exact text depends on the vendor's compiler.
A few other codes to recognize:
| Code | Name | Typical cause |
|---|---|---|
| -1 | CL_DEVICE_NOT_FOUND | No device of the requested type on that platform |
| -5 | CL_OUT_OF_RESOURCES | A kernel faulted, or resources are exhausted |
| -11 | CL_BUILD_PROGRAM_FAILURE | Kernel compile error, read the log |
| -30 | CL_INVALID_VALUE | A bad argument value to an API call |
| -36 | CL_INVALID_COMMAND_QUEUE | Released or wrong queue |
| -48 | CL_INVALID_KERNEL | A kernel that is not valid |
| -52 | CL_INVALID_KERNEL_ARGS | An argument not set before enqueue |
| -54 | CL_INVALID_WORK_GROUP_SIZE | Local size does not divide global size, or exceeds the limit |
The names and values are defined in the cl.h header, and the specification lists which functions can return which.
The kernel language: OpenCL C
Kernels are written in OpenCL C, a dialect of C99 with additions: address space qualifiers, vector types, built-in functions for the work-item model and math, and restrictions. Nearly every C99 feature you rely on survives. Recursion, function pointers and variable-length arrays do not. In OpenCL C 3.0, which the OpenCL C 3.0 specification defines, several features are optional and reported by feature macros, such as __opencl_c_fp64 for double precision and __opencl_c_atomic_order_seq_cst for sequentially consistent atomics. You test the macros with #ifdef inside the kernel source.
A kernel function is marked __kernel and returns void. Pointer parameters carry an address space qualifier saying where the memory lives, which has no equivalent in plain C:
| Qualifier | Meaning | CUDA analog |
|---|---|---|
__global | Device memory visible to all work-items | Global memory |
__constant | Read-only memory with a size limit and a fast path | __constant__ |
__local | Shared by the work-items of one work-group | __shared__ |
__private | One work-item's own memory, the default for locals | Registers and local |
The qualifiers matter because they are part of the pointer type. Passing a __local pointer where a __global pointer is expected is a compile error in OpenCL 1.2 and 3.0 baseline code, since there is no generic pointer unless the device supports the generic address space feature. The built-in functions that give each work-item its coordinates are the ones in the table above, and they take the dimension index as an argument, get_global_id(1) for the second dimension.
Vector types are a first-class part of the language. float4 holds four floats, with component access .x, .y, .z, .w or swizzles like .xy and .wzyx, and arithmetic works component-wise. Wide loads through vload4 and vstore4, or a float4 pointer, let one work-item move 16 bytes at a time, the same vector load idea as in CUDA. Each vector width from 2 to 16 exists for the scalar types.
__kernel void scale4(__global const float4 *in, __global float4 *out, const float k)
{
size_t i = get_global_id(0);
out[i] = in[i] * k; // four multiplications, one 16-byte load and store
}Launch it with a global size of n / 4 if the array has n floats, and an n that is a multiple of 4. Whether the hardware gains from vector types depends on the device: GPUs of the recent generations are scalar machines and gain mostly from the wider memory transactions, while CPU implementations map vectors onto SIMD registers and gain on arithmetic as well.
Choosing global and local sizes
The two sizes you pass to clEnqueueNDRangeKernel are the most consequential numbers in an OpenCL program. The global size is how many work-items run, and for a one-to-one mapping from work-item to element it equals the element count, rounded up. The local size is the work-group shape. Three rules govern it, from the specification and from device limits.
First, each work-group dimension has a maximum, and the product of the dimensions has a maximum, reported by clGetDeviceInfo with CL_DEVICE_MAX_WORK_ITEM_SIZES and CL_DEVICE_MAX_WORK_GROUP_SIZE. A specific kernel can have a lower limit than the device, because of the registers and local memory it uses. Ask the kernel itself:
size_t maxWg = 0, multiple = 0;
clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE,
sizeof(maxWg), &maxWg, NULL);
clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE,
sizeof(multiple), &multiple, NULL);
printf("max work-group size %zu, preferred multiple %zu\n", maxWg, multiple);max work-group size 1024, preferred multiple 32The numbers shown are typical of an NVIDIA GPU and will differ on your device. The preferred multiple is the hardware's execution width, 32 for an NVIDIA warp, often 32 or 64 on AMD and 8 to 32 on Intel, and a local size that is a multiple of it avoids wasting lanes, exactly like the multiple-of-32 rule in CUDA.
Second, in the OpenCL 1.x model, the global size in each dimension must be divisible by the local size. If you give an explicit local size that does not divide the global size, the enqueue fails with CL_INVALID_WORK_GROUP_SIZE. OpenCL 2.0 introduced non-uniform work-group sizes, where the last group in a dimension may be smaller, but it is an optional feature in 3.0 and not available everywhere, so portable code rounds the global size up to a multiple of the local size and guards the kernel with the if (i < n) test, as in the examples:
size_t local = 64;
size_t global = ((n + local - 1) / local) * local;This is the same ceiling division as in CUDA, applied to the work-item count.
Third, you may pass NULL as the local size and let the implementation choose, which is the right default for kernels that do not use local memory or barriers. When a kernel depends on the group size, because it uses barrier and a fixed-size scratch array, you must choose explicitly, and you can state the size in the kernel with an attribute so the compiler can optimize for it:
__kernel __attribute__((reqd_work_group_size(64, 1, 1)))
void reduce(/* ... */);With reqd_work_group_size, launching with any other local size fails, and the compiler may unroll loops and drop checks that depend on the group size.
Local memory and barriers: a work-group reduction
Local memory is the on-chip scratchpad shared by one work-group. The standard use is a tree reduction, the same algorithm as the CUDA version, with a different spelling. Each work-item loads one element into a __local array, the group synchronizes with a barrier, and the stride halves each step:
__kernel void reduce(__global const float *in,
__global float *partial,
__local float *scratch,
const int n)
{
int gid = get_global_id(0);
int lid = get_local_id(0);
int group = get_group_id(0);
scratch[lid] = (gid < n) ? in[gid] : 0.0f;
barrier(CLK_LOCAL_MEM_FENCE);
for (int s = get_local_size(0) / 2; s > 0; s >>= 1) {
if (lid < s) scratch[lid] += scratch[lid + s];
barrier(CLK_LOCAL_MEM_FENCE);
}
if (lid == 0) partial[group] = scratch[0];
}The __local float *scratch parameter is different from other arguments. You do not pass data for it, you pass a size, and the runtime allocates that much local memory per work-group. On the host, set it with the size and a null pointer:
size_t local = 64, global = 256;
clSetKernelArg(kernel, 0, sizeof(cl_mem), &dIn);
clSetKernelArg(kernel, 1, sizeof(cl_mem), &dPartial);
clSetKernelArg(kernel, 2, local * sizeof(float), NULL); // local memory size
clSetKernelArg(kernel, 3, sizeof(int), &n);
clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &global, &local, 0, NULL, NULL);With 256 inputs holding the values 0 to 255, four work-groups of 64 produce partial sums that the host reads back and adds:
2016 6112 10208 14304 total=32640The first group sums 0 to 63, which is 2,016, the second sums 64 to 127, which is 6,112, then 10,208 and 14,304, and the total is the sum of 0 to 255, 32,640. Two points about the barrier. It must be reached by every work-item of the group, so it cannot sit inside a branch that only some items take, exactly like __syncthreads(). And CLK_LOCAL_MEM_FENCE states which memory the barrier orders, local memory here, while CLK_GLOBAL_MEM_FENCE orders global memory accesses within the group. The barrier does not synchronize across work-groups, so the host adds the four partial sums, or a second kernel does.
Two-dimensional problems
Images and matrices map to two dimensions. The NDRange has two sizes, and the kernel asks for each coordinate separately. Here is a matrix multiply, the structure from the CUDA tiled post without the tile:
__kernel void matmul(__global const float *A, __global const float *B,
__global float *C, const int M, const int N, const int K)
{
int col = get_global_id(0); // fastest-varying dimension
int row = get_global_id(1);
if (row < M && col < N) {
float acc = 0.0f;
for (int k = 0; k < K; ++k) acc += A[row * K + k] * B[k * N + col];
C[row * N + col] = acc;
}
}For a 2 by 3 matrix times a 3 by 2 matrix, the host launches a two-dimensional range of {N, M}:
size_t global[2] = { 2, 2 }; // { columns, rows }
clEnqueueNDRangeKernel(queue, kernel, 2, NULL, global, NULL, 0, NULL, NULL);With A holding 1 to 6 row by row and B holding 7 to 12, the result read back is:
58 64
139 154The work_dim argument, 2 here, says how many entries the size arrays have. Dimension 0 is the fastest-varying one, the one that should map to the contiguous direction in memory so neighboring work-items read neighboring addresses, the coalescing rule from CUDA. Putting the column in dimension 0, as above, does that for row-major data. A tiled version with __local arrays follows the same structure as the CUDA one, with barrier(CLK_LOCAL_MEM_FENCE) after each tile load and each tile use.
Memory objects in more detail
Buffers are the main memory object, and the flags you give at creation steer where the runtime puts the data and how you can access it. The access flags CL_MEM_READ_ONLY, CL_MEM_WRITE_ONLY and CL_MEM_READ_WRITE describe how kernels use the buffer, and the runtime may use that to optimize or to reject misuse. The host-pointer flags are:
| Flag | Meaning |
|---|---|
CL_MEM_COPY_HOST_PTR | Allocate device memory and copy the host data in at creation |
CL_MEM_USE_HOST_PTR | Use the host memory as the buffer's storage, allowing zero-copy on shared-memory devices |
CL_MEM_ALLOC_HOST_PTR | Allocate in memory the host can map, commonly pinned memory, the OpenCL counterpart of CUDA's pinned allocation |
Transfers use clEnqueueWriteBuffer and clEnqueueReadBuffer, with a blocking flag. For repeated host access to a buffer, mapping avoids a copy on devices where host and device share memory. clEnqueueMapBuffer returns a host pointer to the buffer's contents, and clEnqueueUnmapMemObject hands it back:
float *p = (float *)clEnqueueMapBuffer(queue, dC, CL_TRUE, CL_MAP_READ,
0, sizeof(c), 0, NULL, NULL, &err);
printf("c[3] = %.0f\n", p[3]);
clEnqueueUnmapMemObject(queue, dC, p, 0, NULL, NULL);c[3] = 33On a discrete GPU, a map of a device buffer typically copies the data to a host-visible staging area, so it is not free, and the real saving appears on integrated GPUs and CPUs. Query CL_DEVICE_HOST_UNIFIED_MEMORY, deprecated in 2.0, or simply measure. To initialize a buffer with a constant, clEnqueueFillBuffer avoids creating a host array just to copy it.
OpenCL 2.0 added shared virtual memory (SVM), pointers valid on both host and device. In 3.0 it is optional, and you check support with clGetDeviceInfo and CL_DEVICE_SVM_CAPABILITIES. Coarse-grained SVM works like CUDA's managed memory with explicit map and unmap, and fine-grained SVM with atomics allows concurrent access. Because many drivers lack it, write the buffer-based path first and add SVM as an option for the devices that report it.
Events, profiling and out-of-order queues
Every enqueue function takes a wait list of events and can return one. An event represents a command's completion, and passing it in another command's wait list creates a dependency. That is how you order work on an out-of-order queue, and how you time a kernel. To profile, enable it when you create the queue, using the property list form of the creation call:
cl_queue_properties props[] = { CL_QUEUE_PROPERTIES, CL_QUEUE_PROFILING_ENABLE, 0 };
cl_command_queue queue = clCreateCommandQueueWithProperties(ctx, device, props, &err);
cl_event ev;
clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &global, &local, 0, NULL, &ev);
clWaitForEvents(1, &ev);
cl_ulong t0, t1;
clGetEventProfilingInfo(ev, CL_PROFILING_COMMAND_START, sizeof(t0), &t0, NULL);
clGetEventProfilingInfo(ev, CL_PROFILING_COMMAND_END, sizeof(t1), &t1, NULL);
printf("kernel time: %.3f ms\n", (t1 - t0) * 1e-6);
clReleaseEvent(ev);kernel time: 0.042 msThe timestamps are in nanoseconds on the device's clock, so the difference is the kernel's execution time, excluding the time the command waited in the queue. The value shown is illustrative. CL_PROFILING_COMMAND_QUEUED, SUBMIT and START give the other stages if you want to see the launch latency. Release every event you receive, or they leak.
A queue is in-order by default: commands run one after another in submission order. Create it with CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE and the runtime may overlap commands that you have not linked through events. To overlap a transfer with a kernel in the CUDA style, you can use two in-order queues on the same device, one for copies and one for kernels, and link them with events, which is the more portable choice. clFlush ensures submitted commands start, and clFinish blocks until all complete.
Compiling kernels: options, caching and SPIR-V
The call clBuildProgram takes an options string. The ones you will use are -D NAME=value to define macros, which is how you specialize a kernel at run time for a tile size or a data type, -cl-std=CL1.2 or -cl-std=CL3.0 to choose the OpenCL C version, and the math options -cl-fast-relaxed-math and -cl-mad-enable, which trade accuracy for speed in the way CUDA's fast math does. Build-time constants let one source file serve many cases:
clBuildProgram(program, 1, &device, "-D TILE=16 -cl-std=CL1.2", NULL, NULL);Because compilation happens when the program runs, it costs start-up time, and large kernels can take noticeable seconds. Cache the compiled binary: after a build, clGetProgramInfo with CL_PROGRAM_BINARIES returns the device binary, which you save to disk and load next time with clCreateProgramWithBinary. A binary is valid only for the same device and driver version, so key the cache by device name and driver version and fall back to source when loading fails. OpenCL 2.1 added clCreateProgramWithIL, which loads SPIR-V, an intermediate representation that other compilers can produce, so kernels can be written in other languages and compiled ahead of time. It is optional in 3.0, and support varies.
Querying the device and writing portable code
Portable OpenCL code does not assume. It asks. A short helper that prints what the device reports saves hours when a program works on one machine and fails on another:
char name[256];
cl_ulong localMem = 0, globalMem = 0;
cl_uint units = 0;
clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(name), name, NULL);
clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(localMem), &localMem, NULL);
clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(globalMem), &globalMem, NULL);
clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(units), &units, NULL);
printf("%s: %u compute units, %llu bytes local, %llu bytes global\n",
name, units, (unsigned long long)localMem, (unsigned long long)globalMem);Example GPU: 28 compute units, 49152 bytes local, 8589934592 bytes globalAgain the numbers are placeholders. The rule is to size local memory use, work-group shape and tile sizes from these values and from the kernel queries, not from constants you measured on your development card. Feature checks follow the same style: read CL_DEVICE_EXTENSIONS for extension names such as cl_khr_fp64, and CL_DEVICE_OPENCL_C_VERSION for the kernel language version. In 3.0, CL_DEVICE_OPENCL_C_FEATURES lists optional OpenCL C features by name.
On a machine with several devices, loop over every platform and device, and pick by criteria such as device type and local memory. A CPU device, typically from the open source POCL project or a vendor CPU runtime, is a valuable second target for testing, since it runs without a GPU, often with stricter checking, and exposes mistakes such as missing barriers differently from a GPU.
Performance: the CUDA lessons apply
The hardware constraints are the same, so the optimization rules carry over from CUDA with new names. Memory access should be coalesced: neighboring work-items in dimension 0 should touch neighboring addresses. Local memory should be used to reuse data, with the same bank conflict arithmetic on devices that have banked local memory, and the same one-element padding fix. Work-group sizes should be multiples of the device's preferred multiple. Branches should be uniform within a sub-group, the OpenCL name for warp or wavefront, to avoid divergence. Registers and local memory limit how many work-groups are resident, so the occupancy trade-offs hold. Reuse values in private memory and give each work-item several independent operations to hide latency.
Two differences deserve emphasis. First, kernel launch overhead and compile time are higher in OpenCL, and you pay for runtime compilation unless you cache binaries. Batch work, and avoid enqueuing thousands of tiny kernels. Second, the tooling is vendor-specific: Nsight Compute can profile OpenCL kernels on NVIDIA hardware through the CUDA driver, AMD and Intel provide their own profilers, and CL_QUEUE_PROFILING_ENABLE events are the portable fallback, as above. Use the events to find the slow kernel, then the vendor tool to find out why.
A small checklist for a new kernel:
Does the global size cover the data, rounded up, with a bounds guard?
Is the fastest-varying dimension the contiguous one in memory?
Is the local size a multiple of the preferred multiple, and below the kernel's maximum?
Do all work-items reach each barrier?
Are the reads and writes to
__globalmemory coalesced, and is reuse moved to__local?Did you check every return code, and print the build log on failure?
Debugging
Debugging tools are weaker than CUDA's. The practical techniques are these. Print from the kernel with printf, which OpenCL C 1.2 introduced and which output appears on the host when the queue finishes. Run the same kernel on a CPU device, where an out-of-range access is more likely to crash or be caught by a sanitizer, and where a debugger can step through host code around the call. Validate results against a plain C reference on small inputs with a floating-point tolerance. Reduce the problem: launch one work-group, or one work-item, with global = 1, and print the intermediate values. Most OpenCL bugs fall into the same families as CUDA ones: a missing bounds guard, a barrier inside a branch, a race on local memory, and a kernel argument of the wrong size.
__kernel void probe(__global const float *in)
{
if (get_global_id(0) == 3) printf("in[3] = %f\n", in[3]);
}in[3] = 3.000000Remember that an argument size mistake is silent at clSetKernelArg for __global pointers in some drivers and appears later as a crash or CL_OUT_OF_RESOURCES, so verify with a one-item run that the values the kernel sees are the values you set.
Structuring a real project
A single main is fine for learning. For a project, wrap the boilerplate in a small layer. A Context struct holds the platform, device, context and queue, created once at start-up from a selection rule. A function buildKernel(ctx, source, name, options) compiles, prints the log on failure and returns a kernel, with a cache keyed by the source hash and device. Kernel source lives in .cl files that the build embeds into the executable as strings, so you edit real OpenCL C with syntax highlighting rather than escaped C strings. Buffers get a small wrapper that owns its cl_mem and releases it, since manual clRelease* calls are the main source of leaks. In C++ the Khronos C++ bindings, CL/opencl.hpp, provide that RAII for free, and many projects use them even when the kernels are the main work.
Where OpenCL fits and where it does not
OpenCL is a good choice when you need one kernel source to run on hardware from several vendors, when you target CPUs and GPUs from one code base, when you work with FPGAs whose toolchains accept OpenCL, or when you maintain an existing OpenCL codebase. It is a weaker choice when you are tied to NVIDIA hardware and want the largest library ecosystem and the best tools, where CUDA wins, when you need graphics interop with a modern API, where Vulkan compute fits better, or when you want a single-source C++ model, where SYCL builds on the same ideas. Driver quality varies, and OpenCL 3.0 optional features mean a program that works on one platform may need a fallback on another. Test on at least two vendors if portability is the reason you chose it.
A worked porting exercise: from CUDA to OpenCL
Porting a small CUDA kernel is the fastest way to check you have the model. Take the CUDA saxpy kernel, which computes y[i] = a * x[i] + y[i] with i built from blockIdx.x * blockDim.x + threadIdx.x. The OpenCL version replaces the index expression with one call and the pointer qualifiers with address spaces:
__kernel void saxpy(const float a, __global const float *x, __global float *y, const int n)
{
int i = get_global_id(0);
if (i < n) y[i] = a * x[i] + y[i];
}On the host, three things change. There is no <<<grid, block>>>, so you compute the global size yourself and pass it to clEnqueueNDRangeKernel. There is no cudaMalloc and cudaMemcpy, so you create buffers with clCreateBuffer and move data with the read and write calls or the host-pointer flags. And there is no implicit compile step, so you build the source string at start-up and check the log. For n = 1000 and a local size of 128, the global size is ((1000 + 127) / 128) * 128, which is 1,024. The 24 surplus work-items fail the i < n test and do nothing, the same tail handling as in CUDA.
Passing a scalar is the detail that surprises people. Each clSetKernelArg call copies the value at that moment, so changing the host variable afterward does not change the kernel's argument. For a you call clSetKernelArg(kernel, 0, sizeof(float), &a) with a float, and passing a double there reads the wrong four bytes without any error. Match the type and size of every argument to the kernel signature, and keep the kernel and the argument-setting code next to each other.
Dealing with several kernels in sequence
Most programs run more than one kernel. Create all the kernels from one program object, keep the intermediate data in buffers on the device, and enqueue the kernels back to back on the same in-order queue. The runtime orders them, so the second kernel sees the first one's output, and the data never travels over the bus between them:
clEnqueueNDRangeKernel(queue, kStage1, 1, NULL, &global, &local, 0, NULL, NULL);
clEnqueueNDRangeKernel(queue, kStage2, 1, NULL, &global, &local, 0, NULL, NULL);
clEnqueueReadBuffer(queue, dOut, CL_TRUE, 0, bytes, host, 0, NULL, NULL);Only the final read is blocking. The two launches return at once, and the read waits for both. If stage 2 needs a different local size from stage 1, pass it per launch. When the stages are independent, use two queues and events so they can overlap, as the profiling section showed. Resist the temptation to call clFinish after every enqueue, which serializes the host and the device and hides the launch overhead you are trying to measure.
Testing OpenCL code
A test for a kernel has four parts: a small deterministic input, a plain C reference, a comparison with a tolerance and boundary sizes. Use sizes of 1, one less than the work-group size, exactly the work-group size and one more, because the bounds guard and the padded global size fail first at those. Run the suite on a CPU device and on a GPU device, since a barrier mistake or a race may pass on one and fail on the other. Print the device name in the test output so a failure tells you which implementation produced it. For floating-point kernels, compare with a relative tolerance near 1e-5 for single precision, and use a looser one for reductions, whose summation order differs from the reference.
Finally, test the error paths on purpose. Pass a local size larger than the kernel's maximum and confirm you get CL_INVALID_WORK_GROUP_SIZE instead of a crash, and break the kernel source on purpose and confirm the build log is printed. Programs whose error handling was never exercised tend to fail silently on the first customer machine whose driver differs from yours.
Reading the specification efficiently
The Khronos specifications are long, and you rarely need to read them end to end. For the host API, the OpenCL API specification has one reference entry per function, with its parameters, return codes and the conditions under which each error is raised. When a call fails with a code you do not understand, find the function's entry and read the error list: it names the exact cause, such as a work-group size that does not divide the global size, or a kernel argument that was never set. For kernel code, the OpenCL C specification lists every built-in function with its overloads, the rules for address spaces and the optional features with their macro names. A good habit is to keep both open while you write your first few kernels, and to read the section on the memory model before you use atomics or fences, since the rules about which writes are visible to which work-items, and when, are stricter than most people assume. A write to local memory is visible to other work-items of the group only after a barrier with the local fence, and a write to global memory is visible to other work-groups only after the kernel ends, unless you use the atomic functions with the proper scope.
Atomics in OpenCL C
Atomic operations let work-items update a shared location without a race. In the baseline 1.2 language they are the atomic_add, atomic_inc, atomic_cmpxchg and related functions on 32-bit integers in global or local memory. The OpenCL C 3.0 specification adds the C11-style atomic types and functions with explicit memory orders and scopes as an optional feature. A histogram in the baseline style looks like this:
__kernel void histogram(__global const uchar *in, __global int *bins, const int n)
{
int i = get_global_id(0);
if (i < n) atomic_inc(&bins[in[i] & 7]);
}As in CUDA, atomics on one address serialize, so a faster version counts in a __local array first and merges once per work-group, with a barrier between the phases. The same advice holds for floating-point sums: there is no portable atomic add for float in the baseline, so reduce with local memory and add the partial results on the host or in a second kernel, as the reduction example above does.


