ข้ามไปยังเนื้อหาหลัก

ติดตั้ง Qiskit C API

คู่มือนี้อธิบายวิธีติดตั้งและใช้งาน Qiskit C API หลังจากติดตั้งเสร็จแล้ว ให้อ่าน ขยาย Python ด้วย Qiskit C API

ตัวอย่างต่อไปนี้สร้าง observable ด้วย C:

// file: example.c
#include <stdio.h>
#include <stdint.h>
#include <qiskit.h>

int main(int argc, char *argv[]) {
// build a 100-qubit empty observable
uint32_t num_qubits = 100;
QkObs *obs = qk_obs_zero(num_qubits);

// add the term 2 * (X0 Y1 Z2) to the observable
QkComplex64 coeff = {2, 0};
QkBitTerm bit_terms[3] = {QkBitTerm_X, QkBitTerm_Y, QkBitTerm_Z};
// bit terms: X Y Z
uint32_t indices[3] = {0, 1, 2}; // indices: 0 1 2
QkObsTerm term = {coeff, 3, bit_terms, indices, num_qubits};
qk_obs_add_term(obs, &term); // append the term

// print some properties and the observable itself
printf("num_qubits: %i\n", qk_obs_num_qubits(obs));
printf("num_terms: %lu\n", qk_obs_num_terms(obs));
printf("observable: %s\n", qk_obs_str(obs));

// free the memory allocated for the observable
qk_obs_free(obs);

return 0;
}

UNIX-like

ส่วนนี้ให้คำแนะนำการ build สำหรับระบบแบบ UNIX

ข้อกำหนดเบื้องต้น

การ compile ต้องใช้เครื่องมือต่อไปนี้:

  • Rust compiler: ดูตัวอย่างได้ที่ คู่มือการติดตั้ง Qiskit จากซอร์ส
  • C compiler: เช่น GCC บน Linux และ Clang บน MacOS Qiskit C API รองรับ compiler ที่สอดคล้องกับมาตรฐาน C11
  • cbindgen: เครื่องมือสร้าง C header ซึ่งติดตั้งได้ด้วย cargo install cbindgen รัน tool จาก command line ต้องเปิดใช้งาน ซึ่งอาจต้องเพิ่ม /path/to/.cargo/bin ลงใน PATH
  • Python library ที่ติดตั้งแล้ว (Python 3.9+): จำเป็นต้องมีในระหว่าง dynamic linking โปรดทราบว่า Python ไม่ได้ถูกใช้งานตอน runtime และ interpreter ไม่เคยถูกเริ่มต้น — ต้องการเพียงบาง symbol จาก libpython เท่านั้น ดูรายละเอียดเพิ่มเติมได้ที่ issue นี้
  • (GNU) Make: ไม่จำเป็น แต่แนะนำให้ใช้สำหรับกระบวนการติดตั้งแบบอัตโนมัติ

โค้ดนี้ตรวจสอบว่าติดตั้งทุกอย่างเรียบร้อยแล้ว:

rustc --version
gcc --version
cbindgen --version
make --version # optional, but recommended

Build

เพื่อ build C header และ library รันคำสั่ง Make ต่อไปนี้1 ใน Qiskit root:

make c

ซึ่งจะให้ shared library ที่ compile แล้วใน dist/c/lib และ header qiskit.h พร้อม function declaration ทั้งหมดใน dist/c/include ชื่อไฟล์ library ที่แน่นอนขึ้นอยู่กับ platform เช่น libqiskit.so บน UNIX และ libqiskit.dylib บน MacOS (หมายเหตุ: ขั้นตอนนี้จะแสดง warning จำนวนมาก ซึ่งเป็นเรื่องปกติและไม่ต้องกังวล เวอร์ชันในอนาคตจะลบ warning เหล่านี้ออก)

จากนั้น compile โปรแกรม C โดยใช้ Qiskit C header และ library:

gcc example.c -o example.o -I /path/to/dist/c/include -L /path/to/dist/c/lib -lqiskit

เพื่อให้แน่ใจว่า Qiskit library ถูกพบในระหว่าง linking ให้กำหนด runtime library path ให้รวม /path/to/dist/c/lib ถ้า Python library ไม่พร้อมใช้งานโดยค่าเริ่มต้นในระหว่าง dynamic linking จะต้องเพิ่มเข้าไปด้วย คำสั่งเหล่านี้แตกต่างกันตาม platform บน Linux:

export LD_LIBRARY_PATH=/path/to/dist/c/lib:$LD_LIBRARY_PATH
# On Linux, the Python library is typically included
# in the dynamic library path by default.
export LD_LIBRARY_PATH=/path/to/python/lib:$LD_LIBRARY_PATH

บน MacOS:

export DYLD_LIBRARY_PATH=/path/to/dist/c/lib:$DYLD_LIBRARY_PATH
export DYLD_LIBRARY_PATH=/path/to/python/lib:$DYLD_LIBRARY_PATH

หรือกำหนด runtime library path ในระหว่าง compilation โดยเพิ่ม

-Wl,-rpath,/path/to/dist/c/lib
# same for Python

เข้าใน compiler flags นอกจากนี้ Python library ต้องพร้อมใช้งานในระหว่าง dynamic linking ซึ่งโดยทั่วไปเป็นค่าเริ่มต้นในสภาพแวดล้อม Linux

ตอนนี้รัน binary ได้เลย:

./example.o

ถ้าใช้ตัวอย่างโค้ดข้างต้น จะได้ผลลัพธ์ดังนี้:

num_qubits: 100
num_terms: 1
observable: SparseObservable { num_qubits: 100,
coeffs: [Complex { re: 2.0, im: 0.0 }],
bit_terms: [X, Y, Z],
indices: [0, 1, 2],
boundaries: [0, 3] }

Windows

ส่วนนี้ให้คำแนะนำการ build สำหรับระบบ Windows

มีสองวิธีที่เป็นอิสระต่อกันในการใช้ C API บน Windows:

  • สร้าง Python extension modules ที่ใช้ Qiskit C API ทำตามขั้นตอนที่ 1-5 วิธีนี้ใช้ C headers ที่มาพร้อมกับแพ็กเกจ Python qiskit และไม่ต้องใช้ Rust หรือ cbindgen

  • สร้าง standalone C library เพื่อเชื่อมโยงจาก C program แท้ ๆ ตามที่ทำในหัวข้อ UNIX-like ทำขั้นตอนที่ 1 ให้เสร็จ แล้วข้ามไปที่ สร้าง standalone library ซึ่งจะแสดงข้อกำหนดเพิ่มเติม

ข้อกำหนดเบื้องต้น

  • บางขั้นตอนต้องใช้สิทธิ์ผู้ดูแลระบบ

  • พื้นที่ดิสก์ว่าง 5-8 GB

  • C compiler: Microsoft Visual C++ (MSVC) ติดตั้งในขั้นตอนที่ 1

  • Python 64-bit (เวอร์ชัน 3.10 หรือใหม่กว่า) ติดตั้งในขั้นตอนที่ 1

ก่อนเริ่มต้น

สร้าง workspace ของคุณ ควรเป็น path สั้น ๆ บนไดรฟ์ในเครื่อง อย่าใช้โฟลเดอร์ที่ sync กับ OneDrive (เช่น Documents หรือ Desktop), network drives หรือ paths ที่มีช่องว่างหรือตัวอักษรที่ไม่ใช่ ASCII หากชื่อผู้ใช้ของคุณมีตัวอักษรที่ไม่ใช่ภาษาอังกฤษ อย่าวางไว้ในโฟลเดอร์ผู้ใช้ของคุณ

ตัวอย่าง workspace paths ที่ดี: C:\workspace, D:\workspace, C:\Users\john\workspace

ขั้นตอนที่ 1 ติดตั้งข้อกำหนดเบื้องต้น

MSVC Build Tools (C compiler) — install this first

นี่คือไฟล์ดาวน์โหลดขนาดใหญ่ (2-5 GB, 10-30 นาที) ติดตั้งสิ่งนี้ก่อนเพื่อให้ทราบทันทีว่าคอมพิวเตอร์ของคุณเข้ากันได้หรือไม่

หมายเหตุ

Requires administrator rights.

ตัวเลือก A — winget เปิด PowerShell terminal และรันสิ่งต่อไปนี้:

winget install Microsoft.VisualStudio.2022.BuildTools --override "--add Microsoft.VisualStudio.Workload.VCTools --includeRecommended --passive --wait"

terminal จะดูเหมือนค้างในขณะที่ตัวติดตั้งกำลังทำงาน ซึ่งเป็นเรื่องปกติและจะใช้เวลา 10-30 นาที ตรวจสอบ taskbar ของคุณสำหรับหน้าต่าง "Visual Studio Installer"

หาก winget ไม่ถูกจดจำ ให้อัปเดต App Installer จาก Microsoft Store หรือใช้ตัวเลือก B

ตัวเลือก B — ดาวน์โหลดด้วยตนเอง เปิดเว็บไซต์ Visual Studio Build Tools for C++ และคลิก Download Build Tools รันไฟล์ executable เพื่อเริ่มการติดตั้ง

เมื่อหน้าต่าง Installing Visual Studio เปิดขึ้น ที่แท็บ Workloads ให้เลือก "Desktop development with C++" ดูหน้า Install C and C++ support in Visual Studio สำหรับรายละเอียดเพิ่มเติม

VS Code

ดาวน์โหลด VS Code จากเว็บไซต์ Visual Studio Code หรือรัน winget install Microsoft.VisualStudio.Code รันไฟล์ executable ที่ดาวน์โหลดมาเพื่อติดตั้ง VS Code

หลังจากติดตั้งแล้ว ให้ทำตามขั้นตอนเหล่านี้ต่อ:

  1. เปิด VS Code
  2. คลิก File → Open Folder แล้วเลือก workspace ของคุณ (ตัวอย่างเช่น C:\workspace)
  3. คลิก Terminal → New terminal เพื่อเปิด PowerShell terminal
  4. คลิกไอคอน Extensions ทางซ้าย หรือกด Ctrl+Shift+X ในหน้าต่าง Extensions ให้ค้นหาและติดตั้ง ms-python.python, ms-toolsai.jupyter และ ms-vscode.cpptools

รันคำสั่งที่เหลือในคู่มือนี้ใน VS Code terminal เว้นแต่จะระบุไว้เป็นอย่างอื่น VS Code terminal จะใช้ PowerShell เป็นค่าเริ่มต้น เพื่อป้องกันความสับสนกับ command window ที่มากับ Windows

ตั้งค่าตัวแปร workspace ตัวอย่างเช่น หาก workspace ของคุณชื่อ workspace ให้รันสิ่งต่อไปนี้:

$WORKSPACE = "C:\workspace" # change to your workspace path
mkdir $WORKSPACE -Force
cd $WORKSPACE
Python 3.12 (recommended version)

แนะนำให้ใช้ Python 3.12 เนื่องจากมี wheel availability ที่ดีที่สุดสำหรับ qiskit-aer และ dependencies อื่น ๆ 3.10 และ 3.11 ก็ใช้งานได้เช่นกัน แต่ 3.13 หรือใหม่กว่าอาจไม่มี pre-built wheels สำหรับบางแพ็กเกจ

เปิด VS Code terminal และรันโค้ดต่อไปนี้เพื่อตรวจหาเวอร์ชัน Python ที่เหมาะสม:

# ── Pre-checks ───────────────────────────────────────────────────────────────
if ($env:CONDA_DEFAULT_ENV -or $env:CONDA_PREFIX) {
Write-Warning "Conda is active. Run 'conda deactivate' first, or open a new terminal."
return
}
if ($env:VIRTUAL_ENV) {
Write-Warning "A virtual environment is active: $env:VIRTUAL_ENV — run 'deactivate' first."
return
}

# ── Detect Python ────────────────────────────────────────────────────────────
$PYTHON_EXE = $null
try {
$ver = (py -3 --version 2>&1) -replace "Python ", ""
$bits = py -3 -c "import platform; print(platform.architecture()[0])"
$path = py -3 -c "import sys; print(sys.executable)"
if ($path -match "(?i)(anaconda|miniconda|miniforge|mambaforge|[/\\]conda[/\\]|[/\\]envs[/\\])") {
Write-Host "Skipping conda-managed Python at: $path"
} elseif ([version]$ver -ge [version]"3.10" -and $bits -eq "64bit") {
$PYTHON_EXE = $path
Write-Host "Python $ver (64-bit) found: $PYTHON_EXE"
} else {
Write-Host "Skipping ($ver, $bits) — need 3.10+ 64-bit"
}
} catch {}
if (-not $PYTHON_EXE) {
try {
$ver = (python --version 2>&1) -replace "Python ", ""
$bits = python -c "import platform; print(platform.architecture()[0])"
$path = python -c "import sys; print(sys.executable)"
if ($path -match "(?i)(anaconda|miniconda|miniforge|mambaforge|[/\\]conda[/\\]|[/\\]envs[/\\])") {
Write-Host "Skipping conda-managed Python at: $path"
} elseif ([version]$ver -ge [version]"3.10" -and $bits -eq "64bit") {
$PYTHON_EXE = $path
Write-Host "Python $ver (64-bit) found: $PYTHON_EXE"
} else {
Write-Host "Skipping ($ver, $bits) — need 3.10+ 64-bit"
}
} catch {}
}

# Install Python 3.12 if it wasn't found.
if (-not $PYTHON_EXE) {
Write-Host "Not found. Installing Python 3.12..."
winget install Python.Python.3.12
Write-Host "Close and reopen the terminal, then rerun this snippet."
}
if ($PYTHON_EXE -and ($PYTHON_EXE -match '[^\x20-\x7E]')) {
Write-Warning "Python path has non-ASCII characters. Keep your workspace on an ASCII path."
}
if ($PYTHON_EXE) { Write-Host "`$PYTHON_EXE = '$PYTHON_EXE'" }

หากการดาวน์โหลดไม่สำเร็จ หรือคุณต้องการดาวน์โหลดด้วยตนเอง ให้ comment out บรรทัดโค้ดที่ติดตั้ง Python 3.12 แล้วดาวน์โหลด Python 3.12 จากเว็บไซต์ Python รันไฟล์ executable เพื่อติดตั้ง Python เลือก "Add Python to PATH" ระหว่างการติดตั้ง แล้วรัน snippet ด้านบนอีกครั้งเพื่อให้แน่ใจว่าพบมันแล้ว

Notes
  • อย่าใช้ Python จาก Microsoft Store เพราะไม่มี C headers หากพิมพ์ python แล้วเปิด Microsoft Store ให้ปิดใช้งาน alias โดยไปที่ Windows Settings → Apps → Advanced app settings → App execution aliases

  • ผู้ใช้ Anaconda: รัน conda deactivate จนกว่า prefix (base) จะหายไป หากไม่หายไป ให้เปิด terminal ใหม่ใน VS Code

Git (optional)

จำเป็นเฉพาะเมื่อคุณ clone lab repositories รัน winget install Git.Git

ขั้นตอนที่ 2 - ตั้งค่า Python virtual environment ด้วย Qiskit

Reset the VS Code terminal

เปิด VS Code terminal และรีเซ็ตมัน:

$WORKSPACE = "C:\workspace" # change to your workspace path
if (-not $PYTHON_EXE) {
if (Get-Command py -ErrorAction SilentlyContinue) { $PYTHON_EXE = py -3 -c "import sys; print(sys.executable)" }
elseif (Get-Command python -ErrorAction SilentlyContinue) { $PYTHON_EXE = python -c "import sys; print(sys.executable)" }
else { Write-Host "Python not found — complete Step 1.3 first." ; return }
Write-Host "`$PYTHON_EXE = '$PYTHON_EXE'"
}
Create and activate a virtual environment

อนุญาตการรัน script (ครั้งเดียวต่อผู้ใช้) จากนั้นสร้าง virtual environment:

Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
cd $WORKSPACE
& $PYTHON_EXE -m venv .venv --prompt workspace
.\.venv\Scripts\Activate.ps1

หากการเปิดใช้งานแสดง error สีแดงเกี่ยวกับ "scripts disabled" แสดงว่ายังไม่ได้รันบรรทัด Set-ExecutionPolicy ให้รันด้วยตนเอง แล้วลองใหม่

ตอนนี้ prompt ของคุณควรแสดง (workspace)

Verify:

Get-Command python | Select-Object -First 1 -ExpandProperty Source
# → workspace\.venv\Scripts\python.exe
Install packages
python -m pip install --upgrade pip setuptools wheel
pip install "qiskit[visualization]>=2.4.2"
pip install --prefer-binary qiskit-ibm-runtime qiskit-aer
pip install notebook ipykernel ipywidgets # optional: run the following Python steps in Jupyter

--prefer-binary หลีกเลี่ยงการคอมไพล์ qiskit-aer จาก source หาก qiskit-aer ยังคงล้มเหลว ให้ลอง pip install qiskit-aer --only-binary=:all: หรือข้ามไป qiskit-aer เป็นตัวเลือกและจำเป็นเฉพาะสำหรับการจำลองในเครื่องเท่านั้น

หมายเหตุ

ห้ามรัน pip install --upgrade qiskit หลังจากตั้งค่าแล้ว การอัปเกรดไปยัง minor version ใหม่จะทำให้ C extension ที่ build จาก version เก่าใช้งานไม่ได้

ขั้นตอนที่ 3 - โหลด MSVC environment

รันโค้ดต่อไปนี้ใน Python session ใหม่แต่ละครั้ง (ตัวอย่างเช่น ทุกครั้งที่คุณรีสตาร์ท Jupyter kernel) มันจะค้นหาและโหลด MSVC developer environment โดยอัตโนมัติ เพื่อให้คุณไม่ต้องใช้ x64 command prompt ที่มากับระบบ

ตัวอย่างในเอกสารนี้สร้าง C extension modules โดยใช้ setuptools กับ MSVC โดยทั่วไปแล้ว คุณจะกำหนด QISKIT_PYTHON_EXTENSION, include qiskit.h และเรียก qk_import() ใน init function ของคุณ มีเพียง headers จาก qiskit.capi.get_include() เท่านั้นที่จำเป็นตอน build time — ไม่มี library ใดถูกลิงก์ ดู ขยาย Qiskit ใน Python ด้วย C สำหรับรายละเอียด

Load the MSVC environment
import os, sys, subprocess, glob, shutil

def load_msvc_env():
if os.name != "nt":
return "Not Windows — the system C compiler is used as-is."
if shutil.which("cl"):
return "cl.exe is already available in this kernel."

pf86 = os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")
pf = os.environ.get("ProgramFiles", r"C:\Program Files")
vcvars = None

vswhere = os.path.join(pf86, "Microsoft Visual Studio", "Installer", "vswhere.exe")
if os.path.isfile(vswhere):
# vswhere outputs UTF-8 regardless of system locale
inst = subprocess.run(
[vswhere, "-latest", "-products", "*",
"-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
"-property", "installationPath"],
capture_output=True, text=True, encoding="utf-8").stdout.strip()
if inst:
cand = os.path.join(inst, "VC", "Auxiliary", "Build", "vcvars64.bat")
if os.path.isfile(cand):
vcvars = cand

if not vcvars:
pat = os.path.join("Microsoft Visual Studio", "*", "*",
"VC", "Auxiliary", "Build", "vcvars64.bat")
hits = glob.glob(os.path.join(pf86, pat)) + glob.glob(os.path.join(pf, pat))
if hits:
vcvars = sorted(hits)[-1]

if not vcvars:
return ("Could not find vcvars64.bat. Install MSVC Build Tools (Step 1.3), "
"or launch Jupyter from the x64 Native Tools Command Prompt.")

# cmd.exe outputs in the OEM codepage (cp437/cp850/etc.), not the ANSI codepage
out = subprocess.run(f'"{vcvars}" >nul 2>&1 && set',
capture_output=True, text=True, encoding="oem", shell=True).stdout
for line in out.splitlines():
if "=" in line:
k, _, v = line.partition("=")
os.environ[k] = v

return ("Loaded MSVC from:\n " + vcvars) if shutil.which("cl") \
else "Ran vcvars64.bat but cl.exe is still not found — check your MSVC install."

print(load_msvc_env())
print("cl.exe on PATH:", shutil.which("cl") is not None)
Verify the setup

ตรวจสอบว่าการตั้งค่าทำงาน:

import importlib.util, shutil

checks = {
"setuptools": importlib.util.find_spec("setuptools") is not None,
"wheel": importlib.util.find_spec("wheel") is not None,
"cl.exe": shutil.which("cl") is not None,
}
for name, ok in checks.items():
print(f" [{'PASS' if ok else 'FAIL':>4}] {name}")

if not checks["cl.exe"]:
print("\n cl.exe is not on PATH. rerun the cell above to load the MSVC environment.")
elif all(checks.values()):
print("\n Toolchain ready. Continue to the smoke test.")

ขั้นตอนที่ 4 - Smoke test: สร้าง C extension

รันโค้ดต่อไปนี้ มันจะเขียน source files ไปยัง _smoke_pkg/, สร้าง C extension โดยอิงกับ Qiskit C API และ import ผลลัพธ์ หากมันพิมพ์ "SMOKE TEST PASSED" แสดงว่า toolchain ของคุณพร้อมแล้ว

แพ็กเกจนี้ทำตามกระบวนการ ขยาย Qiskit ใน Python ด้วย C และใช้ functions จาก เอกสารอ้างอิง Qiskit C API

Smoke test code
import sys, subprocess, pathlib, importlib

root = pathlib.Path("_smoke_pkg")
pkg = root / "src" / "qgss_smoke"
pkg.mkdir(parents=True, exist_ok=True)

(root / "pyworkspace.toml").write_text("""
[build-system]
requires = ["setuptools", "qiskit>=2.4.2"]
build-backend = "setuptools.build_meta"

[workspace]
name = "qgss_smoke"
version = "0.0.1"
dependencies = ["qiskit>=2.4.2"]

[tool.setuptools]
package-dir = {"" = "src"}
""".lstrip())

(root / "setup.py").write_text("""
import qiskit
from setuptools import setup, Extension

core_ext = Extension(
name="qgss_smoke._core",
sources=["src/qgss_smoke/_coremodule.c"],
include_dirs=[qiskit.capi.get_include()],
)
setup(ext_modules=[core_ext])
""".lstrip())

(pkg / "__init__.py").write_text("from . import _core\nbuild_demo = _core.build_demo\n")

(pkg / "_coremodule.c").write_text("""
#define QISKIT_PYTHON_EXTENSION
#include <Python.h>
#include <qiskit.h>
#include <stdint.h>

static PyObject *build_demo(PyObject *self, PyObject *args) {
QkCircuit *qc = qk_circuit_new(2, 0);
uint32_t q0[1] = {0};
qk_circuit_gate(qc, QkGate_H, q0, NULL);
uint32_t q1[1] = {1};
qk_circuit_gate(qc, QkGate_X, q1, NULL);
return qk_circuit_to_python_full(qc);
}

static PyMethodDef core_methods[] = {
{"build_demo", build_demo, METH_NOARGS, "Build a 2-qubit demo circuit in C."},
{NULL, NULL, 0, NULL},
};
static struct PyModuleDef core_module = {
.m_base = PyModuleDef_HEAD_INIT,
.m_name = "_core",
.m_methods = core_methods,
};
PyMODINIT_FUNC PyInit__core(void) {
if (qk_import() < 0) {
return NULL;
}
return PyModuleDef_Init(&core_module);
}
""".lstrip())

# On Windows, an imported .pyd is file-locked by the OS. Drop the module from
# sys.modules BEFORE pip install --force-reinstall, otherwise pip fails with
# WinError 32 ("file in use") trying to overwrite the locked .pyd.
if "qgss_smoke._core" in sys.modules:
del sys.modules["qgss_smoke._core"]
if "qgss_smoke" in sys.modules:
del sys.modules["qgss_smoke"]

r = subprocess.run(
[sys.executable, "-m", "pip", "install", "--no-build-isolation",
"--force-reinstall", "--quiet", str(root.resolve())],
capture_output=True, text=True,
)
if r.returncode != 0:
output = (r.stderr + r.stdout).strip()
print("BUILD FAILED:\n")
print(output)
if "WinError 32" in output or "being used by another process" in output:
print("\n--- TIP ---")
print("The .pyd file is locked because it was previously imported in this kernel.")
print("Restart the kernel (Ctrl+Shift+P → 'Jupyter: Restart Kernel'), then rerun")
print("the Step 3 MSVC cell first, then this cell again.")
elif "cl.exe" in output.lower() or "vcvars" in output.lower() or "cannot find" in output.lower():
print("\n--- TIP ---")
print("The compiler was not found. rerun the Step 3 cell to load the MSVC environment.")
else:
importlib.invalidate_caches()
import qgss_smoke
from qiskit import QuantumCircuit

qc = qgss_smoke.build_demo()
ops = dict(qc.count_ops())
ok = isinstance(qc, QuantumCircuit) and ops.get("h") == 1 and ops.get("x") == 1

print("Returned object is a QuantumCircuit:", isinstance(qc, QuantumCircuit))
print("Gates built in C:", ops)
print("\nSMOKE TEST PASSED — your Windows toolchain can build Qiskit C extensions."
if ok else "\nSomething is off — check the gates above.")

ขั้นตอนที่ 5 — ตั้งค่า VS Code (ตัวเลือก)

เพื่อความสะดวกในการใช้งาน คุณสามารถทำตามกระบวนการนี้เพื่อตั้งค่า IntelliSense สำหรับไฟล์ C และเลือก Python interpreter อัตโนมัติ

Make the .vscode directory

ใน VS Code terminal ให้รันโค้ดต่อไปนี้:

mkdir $WORKSPACE\.vscode -Force
สร้างไฟล์ settings

สร้าง .vscode/settings.json ใน workspace ของคุณโดยรันโค้ดนี้:

{
"python.defaultInterpreterPath": "${workspaceFolder}/.venv/Scripts/python.exe",
"python.terminal.activateEnvironment": true,
"jupyter.notebookFileRoot": "${workspaceFolder}"
}
สร้างไฟล์ properties

โค้ดต่อไปนี้จะพิมพ์ JSON ที่คุณต้องวางลงใน .vscode/c_cpp_properties.json:

import qiskit.capi

inc = qiskit.capi.get_include().replace("\\", "/")
print(".vscode/c_cpp_properties.json — create this file with the content below:\n")
print('{')
print(' "version": 4,')
print(' "configurations": [')
print(' {')
print(' "name": "Win32",')
print(f' "includePath": ["{inc}"],')
print(' "defines": ["QISKIT_PYTHON_EXTENSION"],')
print(' "compilerPath": "cl.exe",')
print(' "cStandard": "c11",')
print(' "intelliSenseMode": "windows-msvc-x64"')
print(' }')
print(' ]')
print('}')
สร้างไฟล์ VS Code extensions

ใน VS Code ให้สร้าง .vscode/extensions.json ด้วยเนื้อหานี้:

{
"recommendations": ["ms-python.python", "ms-toolsai.jupyter", "ms-vscode.cpptools"]
}

สร้าง standalone library

ส่วนนี้จะสร้าง C library แบบ standalone ซึ่งจำเป็นเฉพาะเมื่อคุณต้องการคอมไพล์และลิงก์โปรแกรม C ล้วน ๆ ตามที่อธิบายไว้ในส่วน UNIX-like นอกจากข้อกำหนดเบื้องต้นใน Step 1 แล้ว ยังต้องใช้เครื่องมือต่อไปนี้ด้วย:

  • Rust compiler: ดูตัวอย่างเช่น คู่มือการติดตั้ง Qiskit จาก source

  • cbindgen: เครื่องมือสำหรับสร้าง C header ซึ่งคุณสามารถติดตั้งได้ด้วย cargo install cbindgen ควรเปิดใช้งานการรันเครื่องมือนี้จากบรรทัดคำสั่ง ซึ่งอาจต้องอัปเดตตัวแปร PATH เพื่อรวม path ของ cargo ด้วย

  • การติดตั้ง Python ที่เข้าถึงได้ทั้ง python3.lib และ python3.dll

  • clone ของ Qiskit repository (git clone https://github.com/Qiskit/qiskit.git)

สร้าง standalone library

ขั้นแรก คอมไพล์ dynamic library qiskit_cext โดยรันคำสั่งต่อไปนี้ใน VS Code (PowerShell) terminal ที่ root ของ Qiskit:

$env:PATH = "\path\to\pythonlib;" + $env:PATH
cargo rustc --release --crate-type cdylib -p qiskit-cext

คำสั่งนี้จะสร้าง .dll dynamic library และไฟล์ .dll.lib ที่เกี่ยวข้องใน target/release จากนั้นสร้าง header ด้วย:

cbindgen --crate qiskit-cext --output dist\c\include\qiskit.h

คำสั่งนี้เขียน MSVC-compatible header ใน dist\c\include

ตอนนี้ใช้ cl เพื่อ compile โปรแกรม C ได้แล้ว เพื่อให้ compiler พบ qiskit library เพิ่ม target\release ไว้ใน PATH variable

$env:PATH = "\path\to\target\release;" + $env:PATH
cl example.c qiskit_cext.dll.lib -I\path\to\dist\c\include

ก่อนรัน ให้เพิ่ม path ของ python3.dll

$env:PATH = "\path\to\python3-dll;" + $env:PATH
.\example.exe

จะได้ผลลัพธ์:

num_qubits: 100
num_terms: 1
observable: SparseObservable { num_qubits: 100,
coeffs: [Complex { re: 2.0, im: 0.0 }],
bit_terms: [X, Y, Z],
indices: [0, 1, 2],
boundaries: [0, 3] }

การแก้ไขปัญหา

winget ไม่ถูกจดจำ

อัปเดต App Installer จาก Microsoft Store หรือใช้ลิงก์ดาวน์โหลดแบบ manual ที่เกี่ยวข้อง

cl ไม่ถูกจดจำ

รัน MSVC load cell ใหม่ (Step 3) หรือใช้ x64 Native Tools Command Prompt

python เปิด Microsoft Store

ไปที่ Settings → Apps → Advanced app settings → App execution aliases แล้วปิด python.exe

.ps1 cannot be loaded / scripts ถูกปิดใช้งาน

รัน Set-ExecutionPolicy -Scope CurrentUser RemoteSigned แล้วลองใหม่

cannot open file 'qiskit.h'

รัน python -c "import qiskit.capi; print(qiskit.capi.get_include())" และตรวจสอบว่า path มีอยู่จริง

หา qiskit.capi ไม่พบ

รัน pip install "qiskit[visualization]~=2.4.2"

การสร้าง qiskit-aer ล้มเหลว

รัน pip install qiskit-aer --only-binary=:all: ถ้ายังล้มเหลวอีก ให้ใช้ Python 3.12 หรือข้าม aer ซึ่งเป็นตัวเลือกเสริม

สร้างสำเร็จแต่ import ล้มเหลวเนื่องจาก version error

Qiskit C extension ที่สร้างขึ้นและเวอร์ชัน Qiskit ที่ติดตั้งต้องเป็นเวอร์ชันเดียวกัน ติดตั้ง Qiskit ใหม่ด้วย pip install "qiskit~=2.4.2"

ผมสร้าง C ใหม่แล้วแต่ circuit ไม่เปลี่ยน

C extension ไม่สามารถ re-import ได้ขณะทำงาน รีสตาร์ท kernel รันคำสั่ง MSVC ใหม่ (Step 3) แล้วสร้างใหม่อีกครั้ง

PowerShell script ถูกบล็อก

Set-ExecutionPolicy -Scope CurrentUser RemoteSigned

ข้อผิดพลาดเกี่ยวกับความยาว path

ใช้ root path สั้น ๆ บน C:\ (เช่น C:\workspace หรือ path ที่คุณตั้งไว้ในขั้นตอนการตั้งค่า) หรือเปิดใช้งาน Long Paths: Settings → System → For developers → Long Paths

Conda กำลังทำงานอยู่ (prompt แสดง (base)) หรือการสร้างทำงานแปลก ๆ หลังจากใช้ Anaconda

รัน conda deactivate จนกว่า CONDA_DEFAULT_ENV และ CONDA_PREFIX จะหายไปจาก environment ทั้งคู่ ตรวจสอบด้วย $env:CONDA_PREFIX ถ้ายังคงอยู่ ให้เปิด PowerShell ใหม่ (ไม่ใช่ Anaconda prompt) แล้วลองใหม่จาก Step 2

virtual environment ถูกสร้างจาก Python ที่จัดการโดย conda (ตรวจสอบบรรทัด home = ใน .venv\pyvenv.cfg)

virtual environment สืบทอด C runtime ของ conda และไม่สามารถแก้ไขในตำแหน่งเดิมได้ ลบมันทิ้ง ดาวน์โหลด Python 3.12 จากเว็บไซต์ Python แล้วสร้างใหม่ รัน Remove-Item -Recurse -Force .venv จากนั้นรัน snippet การตรวจจับ Python ใน Step 1 ใหม่เพื่อตั้งค่า $PYTHON_EXE แล้วสร้าง virtual environment ใหม่ (Step 2)

DLL load failed ขณะ import

Conda น่าจะรั่วไหลเข้าไปใน virtual environment ตรวจสอบทั้งสองปัญหาด้านบนนี้ นอกจากนี้ให้ตรวจสอบว่า Python เป็น 64-bit: python -c "import platform; print(platform.architecture())"

การสร้างล้มเหลวด้วย path ที่อ่านไม่ออกหรือ C1083

ชื่อผู้ใช้หรือ path ของ workspace มีอักขระที่ไม่ใช่ ASCII ย้าย workspace ไปยัง path แบบ ASCII-only ที่สั้น (เช่น C:\workspace)

การสร้างหรือ import ล้มเหลวแบบสุ่ม ใช้ได้เมื่อลองใหม่

โฟลเดอร์ workspace ถูกซิงค์โดย OneDrive ย้ายไปยัง path ในเครื่องเช่น C:\workspace

การสร้างถูกขัดจังหวะกลางทาง (เช่น ไฟดับ)

ลบโฟลเดอร์ _smoke_pkg ใน workspace ของคุณ รัน MSVC load cell ใหม่ แล้วรัน smoke test cell ใหม่

pip install ล้มเหลวด้วย SSL certificate error

เครือข่ายของคุณใช้ proxy ที่ดักจับ HTTPS ลองรัน pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org qiskit หรือขอ proxy CA certificate จากผู้ดูแลระบบเครือข่าย

Windows Defender กักกันไฟล์ .pyd

เพิ่มโฟลเดอร์ .venv และ _smoke_pkg ของ workspace ของคุณเข้าไปในรายการยกเว้นของ Defender โดยไปที่ Windows Security → Virus & threat protection → Manage settings → Exclusions

ไม่สามารถติดตั้ง VS Build Tools ได้ (ไม่มีสิทธิ์ admin)

จำเป็นต้องมีสิทธิ์ผู้ดูแลระบบ ขอสิทธิ์เข้าถึงจากแผนก IT ของคุณ

WinError 32 / ไฟล์กำลังถูกใช้งานระหว่างการสร้างใหม่

.pyd ถูกล็อกโดย kernel ที่กำลังทำงานอยู่ รีสตาร์ท kernel (Ctrl+Shift+P → Jupyter: Restart Kernel) รัน Step 3 ใหม่ แล้วสร้างใหม่อีกครั้ง

คำสั่งไม่ทำงานอย่างเงียบ ๆ (ไม่มี error ไม่มี output)

คุณอาจอยู่ใน cmd.exe แทนที่จะเป็น PowerShell ตรวจสอบ prompt ของคุณ: PowerShell แสดง PS C:\> ส่วน cmd แสดง C:\> เปิด PowerShell จาก Start Menu หรือ Win+X

การติดตั้ง MSVC ดูเหมือนค้าง

แฟล็ก --passive --wait จะบล็อก PowerShell ขณะที่ตัวติดตั้งทำงานอยู่เบื้องหลัง ตรวจสอบ taskbar ของคุณเพื่อหาหน้าต่าง "Visual Studio Installer" อาจใช้เวลา 10-30 นาทีในการติดตั้ง

ขั้นตอนถัดไป

Footnotes

  1. ถ้าไม่ได้ติดตั้ง Make ให้ดูไฟล์ Makefile ใน Qiskit root เพื่อดูคำสั่งที่ต้องใช้ — หรือจะติดตั้ง Make ก็ยังไม่สาย