Qiskit C API 설치
이 가이드에서는 Qiskit C API를 설치하고 사용하는 방법을 설명합니다. 설치가 완료되면 Qiskit C API로 Python 확장하기를 읽어보세요.
다음 예제는 C로 observable을 빌드합니다:
// 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 계열
이 섹션에서는 UNIX 계열 시스템에 대한 빌드 방법을 안내합니다.
요구 사항
컴파일에는 다음 도구들이 필요합니다:
- Rust 컴파일러: 예를 들어 소스에서 Qiskit 설치 가이드를 참조하세요.
- C 컴파일러: 예를 들어 Linux에서는 GCC, MacOS에서는 Clang을 사용합니다. Qiskit의 C API는 C11 표준을 준수하는 컴파일러와 호환됩니다.
cbindgen: C 헤더를 생성하는 도구로,cargo install cbindgen명령으로 설치할 수 있습니다. 커맨드 라인에서 도구를 실행할 수 있어야 하며,/path/to/.cargo/bin을 포함하도록PATH변수를 내보내야 할 수도 있습니다.- Python 라이브러리 설치 (Python 3.9+): 동적 링크 시 Python 라이브러리가 필요합니다. Python은 런타임에 사용되지 않으며 인터프리터가 초기화되지 않습니다.
libpython의 일부 심볼만 정의되어야 합니다. 자세한 내용은 이 이슈를 참조하세요. - (GNU) Make: 선택 사항이지만 자동화된 설치 프로세스를 사용하기 위해 권장됩니다.
다음 코드로 모든 것이 올바르게 설치되었는지 확인할 수 있습니다:
rustc --version
gcc --version
cbindgen --version
make --version # optional, but recommended
빌드
C 헤더와 라이브러리를 빌드하려면 Qiskit 루트에서 다음 Make 명령1을 실행하세요.
make c
이 명령을 실행하면 컴파일된 공유 라이브러리가 dist/c/lib에, 모든 함수 선언이 포함된 qiskit.h 헤더가 dist/c/include에 제공됩니다. 라이브러리 이름은 플랫폼에 따라 다릅니다. 예를 들어 UNIX에서는 libqiskit.so, MacOS에서는 libqiskit.dylib입니다.
(현재 이 단계에서 많은 경고가 출력되는데, 이는 예상된 동작이므로 걱정하지 않아도 됩니다. 향후 버전에서는 경고가 제거될 예정입니다.)
그런 다음 Qiskit C 헤더와 라이브러리를 사용하여 C 프로그램을 컴파일할 수 있습니다:
gcc example.c -o example.o -I /path/to/dist/c/include -L /path/to/dist/c/lib -lqiskit
링크 시 Qiskit 라이브러리를 찾을 수 있도록, 런타임 라이브러리 경로에 /path/to/dist/c/lib를 포함시키세요. Python 라이브러리가 동적 링크 시 기본적으로 사용 불가능한 경우, 해당 경로도 추가해야 합니다. 이 명령은 플랫폼에 따라 다릅니다. 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
또는 컴파일 시 다음을 추가하여 런타임 라이브러리 경로를 설정할 수도 있습니다:
-Wl,-rpath,/path/to/dist/c/lib
# same for Python
컴파일러 플래그에 위 옵션을 추가하세요. 또한 동적 링크 시 Python 라이브러리를 사용할 수 있어야 합니다. Linux 환경에서는 일반적으로 기본값으로 설정되어 있습니다.
이제 바이너리를 실행할 수 있습니다:
./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
이 섹션에서는 Windows 시스템에 대한 빌드 방법을 안내합니다.
Windows에서 C API를 사용하는 방법에는 두 가지 독립적인 방법이 있습니다:
-
Qiskit C API를 사용하는 Python 확장 모듈을 빌드합니다. 1-5단계를 따르세요. 이 경로는
qiskitPython 패키지와 함께 제공되는 C 헤더를 사용하며 Rust나 cbindgen이 필요하지 않습니다. -
UNIX-like 섹션에서 수행하는 것처럼 순수 C 프로그램에서 링크할 독립형 C 라이브러리를 빌드합니다. 1단계를 완료한 다음, 추가 요구 사항이 나열된 독립형 라이브러리 빌드하기로 건너뛰세요.
요구 사항
-
일부 단계에는 관리자 권한이 필요합니다.
-
5-8GB의 여유 디스크 공간.
-
C 컴파일러: Microsoft Visual C++(MSVC), 1단계에서 설치됩니다.
-
64비트 Python 설치(3.10 이상), 1단계에서 설치됩니다.
시작하기 전에
작업 공간을 생성하세요. 로컬 드라이브의 짧은 경로여야 합니다. OneDrive와 동기화된 폴더(예: Documents나 Desktop), 네트워크 드라이브, 공백이나 비ASCII 문자가 포함된 경로는 사용하지 마세요. 사용자 이름에 비영어 문자가 포함되어 있다면, 사용자 폴더 아래에 두지 마세요.
좋은 작업 공간 경로의 예: C:\workspace, D:\workspace, C:\Users\john\workspace
1단계. 필수 구성 요소 설치하기
MSVC Build Tools (C 컴파일러) — 먼저 이것을 설치하세요
이것은 대용량 다운로드(2-5GB, 10-30분)입니다. 먼저 설치하여 컴퓨터가 호환되는지 즉시 확인하세요.
Requires administrator rights.
옵션 A — winget
PowerShell 터미널을 열고 다음을 실행하세요:
winget install Microsoft.VisualStudio.2022.BuildTools --override "--add Microsoft.VisualStudio.Workload.VCTools --includeRecommended --passive --wait"
설치 프로그램이 실행되는 동안 터미널이 멈춘 것처럼 보입니다. 이는 정상이며 10-30분 정도 걸립니다. 작업 표시줄에서 "Visual Studio Installer" 창을 확인하세요.
winget이 인식되지 않으면 Microsoft Store에서 App Installer를 업데이트하거나 옵션 B를 사용하세요.
옵션 B — 수동 다운로드 Visual Studio Build Tools for C++ 웹사이트를 열고 Download Build Tools를 클릭합니다. 실행 파일을 실행하여 설치를 시작합니다.
Installing Visual Studio 창이 열리면 Workloads 탭에서 "Desktop development with C++"를 선택합니다. 자세한 내용은 Install C and C++ support in Visual Studio 페이지를 참조하세요.
VS Code
Visual Studio Code 사이트에서 VS Code를 다운로드하거나 winget install Microsoft.VisualStudio.Code를 실행하세요. 다운로드한 실행 파일을 실행하여 VS Code를 설치합니다.
설치가 완료되면 다음 단계를 계속 진행하세요:
- VS Code를 엽니다
- File → Open Folder를 클릭한 다음 작업 공간을 선택합니다(예:
C:\workspace). - Terminal → New terminal을 클릭하여 PowerShell 터미널을 엽니다.
- 왼쪽의 Extensions 아이콘을 클릭하거나 Ctrl+Shift+X를 누릅니다. Extensions 창에서
ms-python.python,ms-toolsai.jupyter,ms-vscode.cpptools를 검색하여 설치합니다.
별도의 지시가 없는 한 이 가이드의 나머지 명령은 VS Code 터미널에서 실행하세요. VS Code 터미널은 기본적으로 PowerShell을 사용하므로 Windows 기본 명령 창과 혼동되지 않습니다.
작업 공간 변수를 설정합니다. 예를 들어 작업 공간의 이름이 workspace라면 다음을 실행하세요:
$WORKSPACE = "C:\workspace" # change to your workspace path
mkdir $WORKSPACE -Force
cd $WORKSPACE
Python 3.12 (권장 버전)
Python 3.12는 qiskit-aer 및 기타 의존성에 대해 최상의 wheel 가용성을 갖추고 있어 권장됩니다. 3.10 및 3.11도 작동하지만 3.13 이상에서는 일부 패키지에 대해 사전 빌드된 wheel이 없을 수 있습니다.
VS Code 터미널을 열고 다음 코드를 실행하여 적합한 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'" }
다운로드가 작동하지 않았거나 수동 다운로드를 선호하는 경우, Python 3.12를 설치하는 코드 줄을 주석 처리한 다음 Python 웹사이트에서 Python 3.12를 다운로드하세요. 실행 파일을 실행하여 Python을 설치합니다. 설치 중 "Add Python to PATH"를 선택한 다음 위의 스니펫을 다시 실행하여 제대로 인식되는지 확인하세요.
-
Microsoft Store의 Python은 C 헤더가 없으므로 사용하지 마세요.
python을 실행했을 때 Microsoft Store가 열리면 Windows Settings → Apps → Advanced app settings → App execution aliases로 이동하여 별칭을 비활성화하세요. -
Anaconda 사용자: (base) 접두사가 사라질 때까지
conda deactivate를 실행하세요. 사라지지 않으면 VS Code에서 새 터미널을 여세요.
Git (선택 사항)
Lab 저장소를 클론하는 경우에만 필요합니다. winget install Git.Git을 실행하세요.
2단계 - Qiskit용 Python 가상 환경 설정
VS Code 터미널 재설정
VS Code 터미널을 열고 재설정합니다:
$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'"
}
가상 환경 생성 및 활성화
(사용자당 한 번) 스크립트 실행을 허용한 다음 가상 환경을 생성합니다:
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
cd $WORKSPACE
& $PYTHON_EXE -m venv .venv --prompt workspace
.\.venv\Scripts\Activate.ps1
활성화 시 "scripts disabled"라는 빨간색 오류가 표시되면 Set-ExecutionPolicy 줄이 실행되지 않은 것입니다. 수동으로 실행한 다음 다시 시도하세요.
이제 프롬프트에 (workspace)가 표시되어야 합니다.
Verify:
Get-Command python | Select-Object -First 1 -ExpandProperty Source
# → workspace\.venv\Scripts\python.exe
패키지 설치
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를 컴파일하는 것을 방지합니다. qiskit-aer가 계속 실패하면 pip install qiskit-aer --only-binary=:all:을 시도하거나 건너뛰세요. qiskit-aer는 선택 사항이며 로컬 시뮬레이션에만 필요합니다.
설정 후에는 pip install --upgrade qiskit을 실행하지 마세요. 새로운 마이너 버전으로 업그레이드하면 이전 버전에 대해 빌드된 C 확장이 손상됩니다.
3단계 - MSVC 환경 로드
새 Python 세션마다(예: Jupyter 커널을 다시 시작할 때마다) 다음 코드를 실행하세요. 이 코드는 x64 기본 명령 프롬프트가 필요 없도록 MSVC 개발자 환경을 자동으로 찾아 로드합니다.
이 문서의 예제는 MSVC와 함께 setuptools를 사용하여 C 확장 모듈을 빌드합니다. 일반적으로 QISKIT_PYTHON_EXTENSION을 정의하고 qiskit.h를 포함시킨 다음 init 함수에서 qk_import()를 호출합니다. 빌드 시에는 qiskit.capi.get_include()의 헤더만 필요하며, 링크되는 라이브러리는 없습니다. 자세한 내용은 Extend Qiskit in Python with C를 참조하세요.
MSVC 환경 로드
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)
설정 확인
설정이 제대로 작동했는지 확인합니다:
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단계 - 스모크 테스트: C 확장 빌드
다음 코드를 실행하세요. 이 코드는 _smoke_pkg/에 소스 파일을 작성하고 Qiskit C API에 대해 C 확장을 빌드한 다음 결과를 임포트합니다. "SMOKE TEST PASSED"가 출력되면 툴체인이 준비된 것입니다.
이 패키지는 Extend Qiskit in Python with C 프로세스를 따르며 Qiskit C API reference의 함수를 사용합니다.
스모크 테스트 코드
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 구성(선택 사항)
사용 편의를 위해 다음 과정을 따라 C 파일에 대한 IntelliSense를 설정하고 Python 인터프리터를 자동으로 선택할 수 있습니다.
.vscode 디렉터리 만들기
VS Code 터미널에서 다음 코드를 실행하세요:
mkdir $WORKSPACE\.vscode -Force
설정 파일 만들기
다음 코드를 실행하여 작업 공간에 .vscode/settings.json을 생성합니다:
{
"python.defaultInterpreterPath": "${workspaceFolder}/.venv/Scripts/python.exe",
"python.terminal.activateEnvironment": true,
"jupyter.notebookFileRoot": "${workspaceFolder}"
}
속성 파일 만들기
다음 코드는 .vscode/c_cpp_properties.json에 붙여넣어야 할 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 확장 파일 만들기
VS Code에서 다음 내용으로 .vscode/extensions.json을 생성하세요:
{
"recommendations": ["ms-python.python", "ms-toolsai.jupyter", "ms-vscode.cpptools"]
}
독립 실행형 라이브러리 빌드
이 섹션에서는 UNIX-like 섹션에 설명된 대로 순수 C 프로그램을 컴파일하고 링크하려는 경우에만 필요한 독립 실행형 C 라이브러리를 빌드합니다. 1단계 필수 조건 외에도 다음 도구가 필요합니다:
-
Rust 컴파일러: 예를 들어 guide on installing Qiskit from source를 참조하세요
-
cbindgen: C 헤더를 생성하는 도구로,cargo install cbindgen으로 설치할 수 있습니다. 명령줄에서 도구를 실행할 수 있어야 하며, 이를 위해PATH변수를 업데이트하여 cargo 경로를 포함해야 할 수도 있습니다. -
python3.lib와python3.dll에 모두 접근할 수 있는 Python 설치 -
Qiskit 저장소의 클론(
git clone https://github.com/Qiskit/qiskit.git)
독립 실행형 라이브러리 빌드
먼저 Qiskit 루트에서 VS Code(PowerShell) 터미널에서 다음을 실행하여 qiskit_cext 동적 라이브러리를 컴파일합니다:
$env:PATH = "\path\to\pythonlib;" + $env:PATH
cargo rustc --release --crate-type cdylib -p qiskit-cext
이렇게 하면 .dll 동적 라이브러리와 관련된 .dll.lib 파일이 target/release에 생성됩니다.
다음으로, 다음을 사용하여 헤더를 생성하세요
cbindgen --crate qiskit-cext --output dist\c\include\qiskit.h
이 명령은 dist\c\include에 MSVC 호환 헤더를 작성합니다.
이제 cl을 사용하여 C 프로그램을 컴파일할 수 있습니다. 컴파일러가 qiskit 라이브러리를 찾을 수 있도록 PATH 변수에 target\release를 포함시킵니다:
$env:PATH = "\path\to\target\release;" + $env:PATH
cl example.c qiskit_cext.dll.lib -I\path\to\dist\c\include
실행하기 전에 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이 인식되지 않음
Microsoft Store에서 App Installer를 업데이트하거나 관련 수동 다운로드 링크를 사용하세요
cl이 인식되지 않음
MSVC 로드 셀(3단계)을 다시 실행하거나 x64 Native Tools Command Prompt를 사용하세요
python을 실행하면 Microsoft Store가 열림
Settings → Apps → Advanced app settings → App execution aliases로 이동하여 python.exe를 끄세요
.ps1 cannot be loaded / 스크립트가 비활성화됨
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned를 실행한 다음 다시 시도하세요
cannot open file 'qiskit.h'
python -c "import qiskit.capi; print(qiskit.capi.get_include())"를 실행하고 경로가 존재하는지 확인하세요
qiskit.capi를 찾을 수 없음
pip install "qiskit[visualization]~=2.4.2"를 실행하세요
qiskit-aer 빌드 실패
pip install qiskit-aer --only-binary=:all:을 실행하세요. 그래도 실패하면 Python 3.12를 사용하거나 선택 사항인 aer를 건너뛰세요
빌드는 실행되지만 임포트가 버전 오류로 실패함
빌드된 Qiskit C 확장과 설치된 Qiskit 버전이 동일해야 합니다. pip install "qiskit~=2.4.2"로 Qiskit을 다시 설치하세요
C를 다시 빌드했지만 Circuit이 변경되지 않음
C 확장은 실행 중에 다시 임포트할 수 없습니다. 커널을 다시 시작하고 MSVC 명령(3단계)을 다시 실행한 다음 다시 빌드하세요
PowerShell 스크립트가 차단됨
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
경로 길이 오류
C:\에 짧은 루트 경로를 사용하세요(예: C:\workspace 또는 설정 단계에서 지정한 경로), 또는 Long Paths를 활성화하세요: Settings → System → For developers → Long Paths
Conda가 활성화되어 있음(프롬프트에 (base)가 표시됨) 또는 Anaconda 사용 후 빌드 동작이 이상함
CONDA_DEFAULT_ENV와 CONDA_PREFIX가 환경에서 모두 사라질 때까지 conda deactivate를 실행하세요. $env:CONDA_PREFIX로 확인하세요. 계속 남아 있으면 (Anaconda prompt가 아닌) 새 PowerShell을 열고 2단계부터 다시 시도하세요.
가상 환경이 conda가 관리하는 Python에서 생성됨(.venv\pyvenv.cfg의 home = 줄 확인)
가상 환경이 conda의 C 런타임을 상속받아 제자리에서 수정할 수 없습니다. 삭제하고 Python 웹사이트에서 Python 3.12를 다운로드한 다음 다시 빌드하세요. Remove-Item -Recurse -Force .venv를 실행한 다음 1단계의 Python 감지 스니펫을 다시 실행하여 $PYTHON_EXE를 설정하고 가상 환경을 다시 생성하세요(2단계).
임포트 시 DLL load failed
Conda가 가상 환경으로 유입되었을 가능성이 있습니다. 바로 위의 두 가지 문제를 모두 확인하세요. 또한 Python이 64비트인지 확인하세요: python -c "import platform; print(platform.architecture())"
경로가 깨지거나 C1083으로 빌드 실패
사용자 이름이나 작업 공간 경로에 ASCII가 아닌 문자가 포함되어 있습니다. 작업 공간을 짧은 ASCII 전용 경로로 이동하세요(예: C:\workspace)
빌드나 임포트가 무작위로 실패하고 재시도하면 작동함
작업 공간 폴더가 OneDrive로 동기화되고 있습니다. C:\workspace와 같은 로컬 경로로 이동하세요
빌드가 중간에 중단됨(예: 정전 발생)
작업 공간의 _smoke_pkg 폴더를 삭제하고 MSVC 로드 셀을 다시 실행한 다음 스모크 테스트 셀을 다시 실행하세요
pip install이 SSL 인증서 오류로 실패
네트워크가 HTTPS를 가로채는 프록시를 사용하고 있습니다. pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org qiskit을 실행하거나 네트워크 관리자에게 프록시 CA 인증서를 요청하세요
Windows Defender가 .pyd 파일을 격리함
Windows Security → Virus & threat protection → Manage settings → Exclusions로 이동하여 작업 공간의 .venv 및 _smoke_pkg 폴더를 Defender 제외 목록에 추가하세요
VS Build Tools를 설치할 수 없음(관리자 권한 없음)
관리자 권한이 필요합니다. IT 부서에 접근 권한을 요청하세요
재빌드 중 WinError 32 / 파일 사용 중
실행 중인 커널이 .pyd 파일을 잠그고 있습니다. 커널을 다시 시작하고(Ctrl+Shift+P → Jupyter: Restart Kernel) 3단계를 다시 실행한 다음 다시 빌드하세요
명령이 아무 반응도 없이 조용히 종료됨(오류도 출력도 없음)
PowerShell이 아닌 cmd.exe에 있을 수 있습니다. 프롬프트를 확인하세요: PowerShell은 PS C:\>를 표시하고 cmd는 C:\>를 표시합니다. 시작 메뉴나 Win+X에서 PowerShell을 여세요
MSVC 설치가 멈춘 것처럼 보임
--passive --wait 플래그는 설치 프로그램이 백그라운드에서 실행되는 동안 PowerShell을 차단합니다. 작업 표시줄에서 "Visual Studio Installer" 창을 확인하세요. 설치에 10~30분이 걸릴 수 있습니다
다음 단계
- Qiskit C API로 Python 확장하기를 배워보세요.
- Qiskit 설치.
- Qiskit C API reference를 살펴보세요.