To compile .cu (CUDA C/C++ source) files into .ptx (Parallel Thread Execution) files, you'll typically use the NVIDIA CUDA Compiler, nvcc.
Here's a step-by-step guide to compiling .cu files into .ptx files:
✅ Prerequisites
- You have CUDA Toolkit installed.
- You're using a terminal or command prompt where
nvcc is in your system path.
You can check by typing:
bash
nvcc --version
🛠️ Basic Command to Compile .cu to .ptx
bash
nvcc -ptx your_kernel.cu -o your_kernel.ptx
This tells nvcc to generate PTX code instead of executable/device code.
🧱 Example
Suppose you have a file named vector_add.cu with a simple kernel:
cpp
// vector_add.cu
__global__ void vectorAdd(int *a, int *b, int *c, int n) {
int i = threadIdx.x;
if (i < n) {
c[i] = a[i] + b[i];
}
}
Compile it to PTX:
bash
nvcc -ptx vectorAdd.cu -o vectorAdd.ptx
Now you’ll have a vectorAdd.ptx file containing the PTX assembly code.
🎯 Optional: Specify GPU Architecture
You can specify the target architecture using -arch=sm_XX, where XX depends on your GPU compute capability.
Example for compute capability 7.5 (Turing):
bash
nvcc -arch=sm_75 -ptx vectorAdd.cu -o vectorAdd.ptx
Available architectures:
| Compute Capability | SM Version |
|---|
| 3.0 | sm_30 |
| 3.5 | sm_35 |
| 5.0 | sm_50 |
| 6.0 | sm_60 |
| 7.0 | sm_70 |
| 7.5 | sm_75 |
| 8.0 | sm_80 |
| 8.6 | sm_86 |
| 8.9 | sm_89 |
| 9.0 | sm_90 |
If you don't specify -arch, nvcc will use a default one.
🔍 Inspect the PTX File
You can open the .ptx file in any text editor or use tools like cat / less to view its contents:
bash
cat vectorAdd.ptx
It will show the intermediate PTX assembly instructions.
📌 Notes
.ptx files are not directly executable on the GPU. They may be compiled further at runtime using Just-In-Time compilation (JIT) by the CUDA driver.
- If you want to embed PTX in host applications (e.g., using CUDA Driver API), this is often useful.
🧪 Advanced Use Case: Separating Compilation Steps
If you're doing more complex builds, you might want to separate steps:
-
Compile CUDA to virtual instruction set (PTX):
bash
nvcc -arch=sm_75 -cubin vectorAdd.cu -o vectorAdd.sm75.cubin
-
Then convert cubin to PTX:
bash
nvcc --cubin-to-ptx vectorAdd.sm75.cubin -o vectorAdd.final.ptx
Let me know if you need help generating PTX for multiple kernels or integrating with Makefiles or CMake!