I-install ang Qiskit C API
Inilalarawan ng gabay na ito kung paano i-install at gamitin ang Qiskit C API. Pagkatapos makumpleto ang pag-install, basahin ang Extend Python with the Qiskit C API.
Ang sumusunod na halimbawa ay gumagawa ng observable gamit ang 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
Ang seksyong ito ay nagbibigay ng mga tagubilin sa pag-build para sa mga UNIX-like na sistema.
Mga Kinakailangan
Ang compilation ay nangangailangan ng mga sumusunod na tools:
- Isang Rust compiler: tingnan halimbawa ang gabay sa pag-install ng Qiskit mula sa source
- Isang C compiler: halimbawa, GCC sa Linux at Clang sa MacOS. Ang Qiskit C API ay compatible sa isang compiler na sumusunod sa pamantayang C11.
cbindgen: isang tool para gumawa ng C header, na maaari mong i-install gamit angcargo install cbindgenDapat mapatakbo ang tool mula sa command line, na maaaring mangailangan ng pag-export ng iyongPATHvariable para isama ang/path/to/.cargo/bin.- Naka-install na Python library (Python 3.9+): Kailangan ang Python library sa panahon ng dynamic linking. Pansinin na hindi ginagamit ang Python sa runtime at hindi kailanman ini-initialize ang interpreter; ilang simbolo lamang mula sa
libpythonang kailangang tukuyin. Tingnan ang isyung ito para sa karagdagang detalye. - (GNU) Make: opsyonal ito ngunit inirerekomenda para sa mga automated na proseso ng pag-install.
Bine-verify ng code na ito na naka-install na ang lahat:
rustc --version
gcc --version
cbindgen --version
make --version # optional, but recommended
Build
Para i-build ang C header at library, maaari kang magpatakbo ng sumusunod na Make command1 sa Qiskit root,
make c
na magbibigay ng compiled shared library sa dist/c/lib at ang qiskit.h header na may
lahat ng function declaration sa dist/c/include. Tandaan na ang eksaktong pangalan ng library ay depende
sa platform; halimbawa, libqiskit.so sa UNIX at libqiskit.dylib sa MacOS.
(Tandaan na ang hakbang na ito ay kasalukuyang naglalabas ng maraming babala, na inaasahan, at walang dapat ipag-alala. Aalisin ng mga susunod na bersyon ang mga babala.)
Maaari mo nang i-compile ang C program gamit ang Qiskit C header at library:
gcc example.c -o example.o -I /path/to/dist/c/include -L /path/to/dist/c/lib -lqiskit
Para masiguro na mahahanap ang Qiskit library sa panahon ng linking, itakda ang runtime library path para
isama ang /path/to/dist/c/lib. Kung ang Python library ay hindi available bilang default sa panahon ng dynamic linking,
kailangan din itong idagdag. Ang mga command na ito ay depende sa platform. Sa 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
Sa MacOS:
export DYLD_LIBRARY_PATH=/path/to/dist/c/lib:$DYLD_LIBRARY_PATH
export DYLD_LIBRARY_PATH=/path/to/python/lib:$DYLD_LIBRARY_PATH
Bilang alternatibo, maaari mong itakda ang runtime library path sa panahon ng compilation sa pamamagitan ng pagdaragdag ng
-Wl,-rpath,/path/to/dist/c/lib
# same for Python
sa mga compiler flag. Bukod pa rito, kailangan na available ang Python library sa panahon ng dynamic linking. Sa mga Linux environment ito ay karaniwang default.
Maaari mo na ngayong i-execute ang binary:
./example.o
na, kung gagamitin ang halimbawang snippet na ipinakita kanina, ay dapat mag-print ng
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
Ang seksyong ito ay nagbibigay ng mga tagubilin sa pag-build para sa mga Windows system.
May dalawang magkahiwalay na paraan upang gamitin ang C API sa Windows:
-
Bumuo ng Python extension modules na gumagamit ng Qiskit C API. Sundan ang Steps 1-5. Ang landas na ito ay gumagamit ng mga C header na kasama sa
qiskitPython package at hindi nangangailangan ng Rust o cbindgen. -
Bumuo ng standalone C library upang i-link mula sa isang purong C program, tulad ng ginagawa sa UNIX-like section. Kumpletuhin ang Step 1, pagkatapos ay lumaktaw sa Build the standalone library, na naglilista ng mga karagdagang requirement nito.
Mga Kinakailangan
-
Kinakailangan ang mga karapatan bilang administrator para sa ilang hakbang.
-
5-8 GB na libreng disk space.
-
Isang C compiler: Microsoft Visual C++ (MSVC), na na-install sa Step 1.
-
Isang 64-bit na Python installation (3.10 o mas bago), na na-install sa Step 1.
Bago ka magsimula
Gumawa ng iyong workspace. Dapat itong maikling path sa isang local drive. Huwag gumamit ng mga OneDrive-synced na folder (tulad ng Documents o Desktop), network drives, o mga path na may spaces o non-ASCII na mga character. Kung ang iyong username ay naglalaman ng non-English na mga character, huwag ilagay ito sa ilalim ng iyong user folder.
Mga halimbawa ng magandang workspace paths: C:\workspace, D:\workspace, C:\Users\john\workspace
Step 1. I-install ang mga prerequisite
MSVC Build Tools (C compiler) — i-install ito muna
Ito ay isang malaking download (2-5 GB, 10-30 min). I-install ito muna upang agad mong malaman kung compatible ang iyong computer.
Requires administrator rights.
Option A — winget
Magbukas ng PowerShell terminal at patakbuhin ang sumusunod:
winget install Microsoft.VisualStudio.2022.BuildTools --override "--add Microsoft.VisualStudio.Workload.VCTools --includeRecommended --passive --wait"
Magmumukhang frozen ang terminal habang tumatakbo ang installer. Normal ito at aabutin ng 10-30 minuto. Tingnan ang iyong taskbar para sa isang "Visual Studio Installer" window.
Kung hindi kinikilala ang winget, i-update ang App Installer mula sa Microsoft Store, o gamitin ang Option B.
Option B — manu-manong pag-download Buksan ang Visual Studio Build Tools for C++ website at i-click ang Download Build Tools. Patakbuhin ang executable upang simulan ang pag-install.
Kapag nagbukas ang Installing Visual Studio window, sa Workloads tab, piliin ang "Desktop development with C++". Tingnan ang Install C and C++ support in Visual Studio page para sa karagdagang detalye.
VS Code
I-download ang VS Code mula sa Visual Studio Code site, o patakbuhin ang winget install Microsoft.VisualStudio.Code. Patakbuhin ang na-download na executable file upang i-install ang VS Code.
Pagkatapos ma-install, ipagpatuloy ang mga hakbang na ito:
- Buksan ang VS Code
- I-click ang File → Open Folder, pagkatapos ay piliin ang iyong workspace (halimbawa,
C:\workspace). - I-click ang Terminal → New terminal upang magbukas ng PowerShell terminal.
- I-click ang Extensions icon sa kaliwa o pindutin ang Ctrl+Shift+X. Sa Extensions window, hanapin at i-install ang
ms-python.python,ms-toolsai.jupyter, atms-vscode.cpptools.
Patakbuhin ang natitirang mga command sa gabay na ito sa VS Code terminal, maliban kung iba ang nakasaad. Ang VS Code terminal ay default na PowerShell, na nag-iiwas sa paghahalo sa built-in na command window ng Windows.
Itakda ang workspace variable. Halimbawa, kung ang iyong workspace ay tinatawag na workspace, patakbuhin ang sumusunod:
$WORKSPACE = "C:\workspace" # change to your workspace path
mkdir $WORKSPACE -Force
cd $WORKSPACE
Python 3.12 (inirerekomendang bersyon)
Inirerekomenda ang Python 3.12 dahil mayroon itong pinakamahusay na wheel availability para sa qiskit-aer at iba pang dependency. Gumagana rin ang 3.10 at 3.11, ngunit maaaring kulang ng mga pre-built na wheel ang 3.13 o mas bago para sa ilang package.
Buksan ang VS Code terminal at patakbuhin ang sumusunod na code upang matukoy ang angkop na bersyon ng 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'" }
Kung hindi gumana ang pag-download, o mas gusto mo ang manu-manong pag-download, i-comment out ang mga linya ng code na nag-i-install ng Python 3.12, pagkatapos ay i-download ang Python 3.12 mula sa Python website. Patakbuhin ang executable upang i-install ang Python. Piliin ang "Add Python to PATH" habang nag-i-install, pagkatapos ay muling patakbuhin ang snippet sa itaas upang matiyak na nahanap ito.
-
HUWAG gamitin ang Microsoft Store Python dahil kulang ito ng C headers. Kung binubuksan ng
pythonang Microsoft Store, i-disable ang alias sa pamamagitan ng pagpunta sa Windows Settings → Apps → Advanced app settings → App execution aliases. -
Mga gumagamit ng Anaconda: patakbuhin ang
conda deactivatehanggang mawala ang (base) prefix. Kung hindi ito mawala, magbukas ng bagong terminal sa VS Code.
Git (opsyonal)
Kailangan lamang kung magcco-clone ka ng mga lab repository. Patakbuhin ang winget install Git.Git.
Step 2 - I-set up ang Python virtual environment gamit ang Qiskit
I-reset ang VS Code terminal
Buksan ang VS Code terminal at i-reset ito:
$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'"
}
Gumawa at i-activate ang isang virtual environment
Payagan ang script execution (isang beses bawat user), pagkatapos ay gumawa ng virtual environment:
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
cd $WORKSPACE
& $PYTHON_EXE -m venv .venv --prompt workspace
.\.venv\Scripts\Activate.ps1
Kung nagpapakita ang activation ng pulang error tungkol sa "scripts disabled", hindi na-run ang linyang Set-ExecutionPolicy. Patakbuhin ito nang manu-mano, pagkatapos ay subukan ulit.
Dapat ay ipinapakita na ngayon ng iyong prompt ang (workspace).
Verify:
Get-Command python | Select-Object -First 1 -ExpandProperty Source
# → workspace\.venv\Scripts\python.exe
I-install ang mga package
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
Iniiwasan ng --prefer-binary ang pag-compile ng qiskit-aer mula sa source. Kung nabigo pa rin ang qiskit-aer, subukan ang pip install qiskit-aer --only-binary=:all: o laktawan ito. Opsyonal ang qiskit-aer at kailangan lamang para sa lokal na simulation.
HUWAG patakbuhin ang pip install --upgrade qiskit pagkatapos ng setup. Ang pag-upgrade sa bagong minor version ay sumisira sa mga C extension na binuo laban sa lumang bersyon.
Step 3 - I-load ang MSVC environment
Patakbuhin ang sumusunod na code sa bawat bagong Python session (halimbawa, sa tuwing nire-restart mo ang isang Jupyter kernel). Awtomatiko nitong hinahanap at nilo-load ang MSVC developer environment kaya hindi mo na kailangan ang built-in na x64 command prompt.
Bumubuo ang halimbawa sa dokumentasyong ito ng mga C extension module gamit ang setuptools kasama ang MSVC. Sa pangkalahatan, dine-define mo ang QISKIT_PYTHON_EXTENSION, isinasama ang qiskit.h, at tinatawag ang qk_import() sa iyong init function. Mga header lang mula sa qiskit.capi.get_include() ang kailangan sa build time — walang naka-link na library. Tingnan ang Extend Qiskit in Python with C para sa mga detalye.
I-load ang 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)
I-verify ang setup
I-verify na gumana ang 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.")
Hakbang 4 - Smoke test: Bumuo ng C extension
Patakbuhin ang sumusunod na code. Isinusulat nito ang mga source file sa _smoke_pkg/, bumubuo ng C extension laban sa Qiskit C API, at ini-import ang resulta. Kung nag-print ito ng "SMOKE TEST PASSED", handa na ang iyong toolchain.
Sinusunod ng package ang proseso ng Extend Qiskit in Python with C at gumagamit ng mga function mula sa Qiskit C API reference.
Smoke test na 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.")
Step 5 — I-configure ang VS Code (opsyonal)
Para sa kadalian ng paggamit, maaari mong sundin ang prosesong ito upang i-set up ang IntelliSense para sa mga C file at awtomatikong piliin ang Python interpreter.
Gumawa ng .vscode directory
Sa VS Code terminal, patakbuhin ang sumusunod na code:
mkdir $WORKSPACE\.vscode -Force
Gumawa ng settings file
Gumawa ng .vscode/settings.json sa iyong workspace sa pamamagitan ng pagpapatakbo ng code na ito:
{
"python.defaultInterpreterPath": "${workspaceFolder}/.venv/Scripts/python.exe",
"python.terminal.activateEnvironment": true,
"jupyter.notebookFileRoot": "${workspaceFolder}"
}
Gumawa ng properties file
Nag-print ang sumusunod na code ng JSON na kailangan mong i-paste sa .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('}')
Gumawa ng VS Code extensions file
Sa VS Code, gumawa ng .vscode/extensions.json na may nilalamang ito:
{
"recommendations": ["ms-python.python", "ms-toolsai.jupyter", "ms-vscode.cpptools"]
}
Buuin ang standalone library
Bumubuo ang seksyong ito ng standalone C library, na kailangan lamang kung gusto mong i-compile at i-link ang mga purong C program, tulad ng inilarawan sa seksyong UNIX-like. Bilang karagdagan sa mga prerequisite sa Step 1, kailangan nito ang sumusunod na mga tool:
-
Isang Rust compiler: tingnan halimbawa ang gabay sa pag-install ng Qiskit mula sa source
-
cbindgen: isang tool para gumawa ng C header, na maaari mong i-install gamit angcargo install cbindgen. Dapat pinagana ang pagpapatakbo ng tool mula sa command line, na maaaring mangailangan ng pag-update sa iyongPATHvariable upang isama ang cargo path. -
Isang Python installation na may access sa parehong
python3.libatpython3.dll -
Isang clone ng Qiskit repository (
git clone https://github.com/Qiskit/qiskit.git)
Buuin ang standalone library
Una, i-compile ang qiskit_cext dynamic library, sa pamamagitan ng pagpapatakbo ng sumusunod sa VS Code (PowerShell) terminal sa Qiskit root:
$env:PATH = "\path\to\pythonlib;" + $env:PATH
cargo rustc --release --crate-type cdylib -p qiskit-cext
Gagawa ito ng .dll dynamic library at ang kasamang .dll.lib file sa target/release.
Susunod, gumawa ng header gamit ang
cbindgen --crate qiskit-cext --output dist\c\include\qiskit.h
Isinusulat nito ang MSVC-compatible na header sa dist\c\include.
Maaari mo na ngayong gamitin ang cl para i-compile ang C program. Para masiguro na mahahanap ng compiler ang qiskit library,
isama ang target\release sa PATH variable.
$env:PATH = "\path\to\target\release;" + $env:PATH
cl example.c qiskit_cext.dll.lib -I\path\to\dist\c\include
Bago patakbuhin, isama ang path sa iyong python3.dll.
$env:PATH = "\path\to\python3-dll;" + $env:PATH
.\example.exe
ay dapat na mag-print ng
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] }
Pag-troubleshoot
Hindi nakikilala ang winget
I-update ang App Installer mula sa Microsoft Store, o gamitin ang kaugnay na mga manual na link sa pag-download
Hindi nakikilala ang cl
Patakbuhin ulit ang MSVC load cell (Hakbang 3), o gamitin ang x64 Native Tools Command Prompt
Binubuksan ng python ang Microsoft Store
Pumunta sa Settings → Apps → Advanced app settings → App execution aliases at i-off ang python.exe
.ps1 cannot be loaded / naka-disable ang mga script
Patakbuhin ang Set-ExecutionPolicy -Scope CurrentUser RemoteSigned pagkatapos ay subukan ulit
cannot open file 'qiskit.h'
Patakbuhin ang python -c "import qiskit.capi; print(qiskit.capi.get_include())" at kumpirmahin na umiiral ang path
Hindi mahanap ang qiskit.capi
Patakbuhin ang pip install "qiskit[visualization]~=2.4.2"
Nabigo ang build ng qiskit-aer
Patakbuhin ang pip install qiskit-aer --only-binary=:all:. Kung nabigo rin iyon, gamitin ang Python 3.12 o laktawan ang aer, na opsyonal
Tumatakbo ang build ngunit nabigo ang import dahil sa version error
Ang binuong Qiskit C extension at ang na-install na bersyon ng Qiskit ay dapat magkaparehong bersyon. I-reinstall ang Qiskit gamit ang pip install "qiskit~=2.4.2"
Muli kong binuo ang C ngunit hindi nagbago ang circuit
Hindi maaaring i-re-import nang live ang isang C extension. I-restart ang kernel, patakbuhin ulit ang mga MSVC command (Hakbang 3), pagkatapos ay muling buuin
Na-block ang PowerShell script
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
Mga error sa haba ng path
Gumamit ng maikling root path sa C:\ (halimbawa, C:\workspace, o ang path na itinakda mo sa hakbang ng setup), o paganahin ang Long Paths: Settings → System → For developers → Long Paths
Aktibo ang Conda (ipinapakita ng prompt ang (base)) o kakaiba ang kilos ng mga build pagkatapos gumamit ng Anaconda
Patakbuhin ang conda deactivate hanggang mawala ang parehong CONDA_DEFAULT_ENV at CONDA_PREFIX mula sa environment. Suriin gamit ang $env:CONDA_PREFIX. Kung nagpapatuloy pa rin ang mga ito, magbukas ng bagong PowerShell (hindi Anaconda prompt) at subukan ulit mula sa Hakbang 2.
Ginawa ang virtual environment mula sa isang conda-managed na Python (tingnan ang linyang home = sa .venv\pyvenv.cfg)
Namana ng virtual environment ang C runtime ng conda at hindi ito maaaring ayusin sa lugar. Burahin ito, i-download ang Python 3.12 mula sa Python website, at muling buuin. Patakbuhin ang Remove-Item -Recurse -Force .venv, pagkatapos ay patakbuhin ulit ang Python detection snippet sa Hakbang 1 upang itakda ang $PYTHON_EXE, pagkatapos ay gawin ulit ang virtual environment (Hakbang 2).
DLL load failed sa import
Malamang na tumatagas ang Conda sa virtual environment. Suriin ang dalawang isyu na nasa itaas mismo nito. I-verify din na 64-bit ang Python: python -c "import platform; print(platform.architecture())"
Nabigo ang build na may sirang mga path o C1083
Naglalaman ang iyong username o workspace path ng mga non-ASCII na character. Ilipat ang workspace sa maikling ASCII-only na path (halimbawa, C:\workspace)
Random na nabibigo ang build o import, gumagana sa muling pagsubok
Naka-sync ang workspace folder gamit ang OneDrive. Ilipat ito sa lokal na path tulad ng C:\workspace
Naantala ang build sa gitna (halimbawa, nagkaroon ng power loss)
Burahin ang _smoke_pkg folder sa iyong workspace, patakbuhin ulit ang MSVC load cell, pagkatapos ay patakbuhin ulit ang smoke test cell
Nabigo ang pip install dahil sa SSL certificate error
Gumagamit ang iyong network ng proxy na humaharang sa HTTPS. Subukang patakbuhin ang pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org qiskit o hilingin sa iyong network administrator ang proxy CA certificate
Kina-quarantine ng Windows Defender ang .pyd file
Idagdag ang .venv at _smoke_pkg folder ng iyong workspace sa Defender exclusions sa pamamagitan ng pagpunta sa Windows Security → Virus & threat protection → Manage settings → Exclusions
Hindi ma-install ang VS Build Tools (walang admin rights)
Kinakailangan ang administrator access. Hilingin sa iyong IT department ang access
WinError 32 / ginagamit ang file habang muling binubuo
Naka-lock ang .pyd ng tumatakbong kernel. I-restart ang kernel (Ctrl+Shift+P → Jupyter: Restart Kernel), patakbuhin ulit ang Hakbang 3, pagkatapos ay muling buuin
Tahimik na walang ginagawa ang mga command (walang error, walang output)
Maaaring nasa cmd.exe ka sa halip na PowerShell. Suriin ang iyong prompt: ipinapakita ng PowerShell ang PS C:\>, ipinapakita ng cmd ang C:\>. Buksan ang PowerShell mula sa Start Menu o Win+X
Mukhang natigil ang pag-install ng MSVC
Hinaharang ng mga flag na --passive --wait ang PowerShell habang tumatakbo ang installer sa background. Suriin ang iyong taskbar para sa isang "Visual Studio Installer" na window. Maaaring umabot ng 10-30 minuto ang pag-install
Mga susunod na hakbang
- Alamin kung paano i-extend ang Python gamit ang Qiskit C API.
- I-install ang Qiskit.
- Galugarin ang Qiskit C API reference.