Declare a CUDA kernel with __global__
Mark a function __global__ in CUDA 12 so the host launches it and the device runs it, returning void, and see which qualifiers may call which.
A CUDA kernel is an ordinary function with one qualifier in front of it. __global__ means "called from the host, runs on the device", and that decides everything else about it: it must return void, it cannot be a member of a class that is not static, and you start it with the launch syntax rather than a call. CUDA 12.
#include <cstdio>
__global__ void scale(float *x, float k, int n)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) x[i] *= k;
}
int main()
{
float h[4] = {1, 2, 3, 4};
float *d;
cudaMalloc(&d, sizeof h);
cudaMemcpy(d, h, sizeof h, cudaMemcpyHostToDevice);
scale<<<1, 4>>>(d, 2.0f, 4);
cudaMemcpy(h, d, sizeof h, cudaMemcpyDeviceToHost);
printf("%g %g %g %g\n", h[0], h[1], h[2], h[3]);
cudaFree(d);
return 0;
}2 4 6 8The qualifiers are summarised in the CUDA C++ Programming Guide. __device__ functions run on the device and are called only from device code; __host__ is the default. A __global__ function may also be called from another kernel when you build with dynamic parallelism, but that is a separate feature.
The launch is asynchronous: control returns before the kernel finishes, and the later cudaMemcpy is what waits for it. Compile with nvcc scale.cu -o scale. The if (i < n) guard is there because a grid is rounded up to whole blocks.