はじめに
Zigでは、zig c++サブコマンドを介してC++のソースコードをコンパイルすることができる。
これは内部でclangがキックされるラッパーとなっている。
zig c++で特にオプションを指定しない場合、LLVMのlibc++がC++ランタイムとして選択されてリンクされる。
MacOSではclangが標準コンパイラなのでlibc++でも困らないが、Linuxのディストロではgccが標準コンパイラであり、そのC++ランタイムはlibstdc++。
ZigからC++のライブラリのAPIを使う場合、ランタイムのAPIが異なるためリンクできない。
この記事では悪戦苦闘の末にzig c++でランタイムとしてlibstdc++を使わせるようわららせることができたので、その記録を残す。
TL;DR
-
build.zigのExecutableに引き渡すstd.Build.Moduleを構成する際に以下のオプションを指定する-
link_libcppにfalseを指定する -
link_libにtrueを指定する
-
-
libstdc++のインクルードパスを構成する
// Ubuntu 24.04の場合
exe.root_module.addIncludePath(.{.cwd_relative = "/usr/include/c++/13"});
exe.root_module.addIncludePath(.{.cwd_relative = "/usr/include/x86_64-linux-gnu/c++/13"});
exe.root_module.addIncludePath(.{.cwd_relative = "/usr/include"});
exe.root_module.addIncludePath(.{.cwd_relative = "/usr/include/x86_64-linux-gnu"});
-
std.Build.Module.addObjectFile()関数を介してC++ランタイムを指定する
// Ubuntu 24.04の場合
exe.root_module.addObjectFile(.{.cwd_relative = "/usr/lib/gcc/x86_64-linux-gnu/13/libstdc++.so"});
exe.root_module.addObjectFile(.{.cwd_relative = "/usr/lib/x86_64-linux-gnu/libgcc_s.so.1"});
この構成でzig buildを実行することで、libstdc++がリンクされた実行ファイルを生成することができる
# nm -C zig-out/bin/test | grep basic_string
0000000001016610 T foo(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
libstdc++のABIである__cxx11となっていることがわかる。
検証環境
- docker desktop v4.61.0上に構築した
Ubuntu 24.04イメージ - Zig v0.16.0
FROM ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y \
curl \
xz-utils \
binutils \
g++ \
libc6-dev \
libstdc++-13-dev \
&& rm -rf /var/lib/apt/lists/*
# Zig install
ARG ZIG_VERSION=0.16.0
RUN curl -L https://ziglang.org/download/0.16.0/zig-x86_64-linux-${ZIG_VERSION}.tar.xz \
-o zig.tar.xz && \
tar -xf zig.tar.xz && \
mv zig-x86_64-linux-* /opt/zig && \
ln -s /opt/zig/zig /usr/local/bin/zig
ENV PATH="/opt/zig:${PATH}"
WORKDIR /work
補足
-
g++- GCC 本体
/usr/lib/gcc/x86_64-linux-gnu/13/-
libstdc++.soなどのリンクのため
-
libc6-dev-
glibcヘッダ /usr/include-
getauxvalなどのlibcシンボルのリンクのため
-
-
libstdc++-13-dev- libstdc++ ヘッダ
/usr/include/c++/13/usr/include/x86_64-linux-gnu/c++/13- 標準C++のヘッダーファイルのインクルードのため
ビルドするソースファイル
#include <string>
auto foo(std::string const&) -> void {}
auto main() -> int {
return 0;
}
まずはそのままビルドする
$ zig c++ -o test src/main.cpp
$ nm -C test | grep basic_string
0000000001001500 T foo(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
libc++のABIである__1となっている。
libstdc++をリンクしてみる
$ zig c++ -o test src/m2.cpp -lstdc++
$ nm -C test | grep basic_string
0000000001001500 T foo(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
libstdc++を指定したのにlibc++ABIである__1のまま・・・。
実行を度外視してまずはlibstdc++のAPIでコンパイルさせる
zig c++のコマンドラインオプションを覗くとnostdinc++が見つかる。
libc++の使用をやめさせるためこれを指定する。
$ zig c++ -o test src/m2.cpp -nostdinc++
src/m2.cpp:1:10: fatal error: 'string' file not found
1 | #include <string>
| ^~~~~~~~
1 error generated.
標準C++ヘッダを無効にしたため当然見つからなくなりコンパイルエラーとなる。
この状態でlibstdc++ヘッダのパスを教える
$ zig c++ \
-nostdinc++ \
-isystem /usr/include/c++/13 \
-isystem /usr/include/x86_64-linux-gnu/c++/13 \
-o test \
src/main.cpp
In file included from src/m2.cpp:1:
In file included from /usr/include/c++/13/string:54:
In file included from /usr/include/c++/13/bits/basic_string.h:4109:
In file included from /usr/include/c++/13/ext/string_conversions.h:43:
/usr/include/c++/13/cstdlib:79:15: fatal error: 'stdlib.h' file not found
79 | #include_next <stdlib.h>
| ^~~~~~~~~~
1 error generated.
std::stringは解消しているが、その中から参照されるstdlib.hが見つからないと仰られる。
Ubuntu 24.04のapt経由でインストールした場合、stdlib.hは/usr/includeに配置されるので、このパスをインクルードパスとして指定する。
# zig c++ \
-nostdinc++ \
-isystem /usr/include/c++/13 \
-isystem /usr/include/x86_64-linux-gnu/c++/13 \
-isystem /usr/include \
-o test \
src/main.cpp
In file included from src/m2.cpp:1:
In file included from /usr/include/c++/13/string:54:
In file included from /usr/include/c++/13/bits/basic_string.h:4109:
In file included from /usr/include/c++/13/ext/string_conversions.h:43:
/usr/include/c++/13/cstdlib:79:15: fatal error: 'stdlib.h' file not found
79 | #include_next <stdlib.h>
| ^~~~~~~~~~
1 error generated.
なぜか解消しない。いとおかし。
ここで行き詰まる。
身長178cmから繰り出されるネットサーフィンのテクニックを駆使して以下の記事に辿り着く。
この記事において-isystemではなく-Iでインクルードパスを指定している。
この記事に倣い変更してみた。
# zig c++ \
-nostdinc++ \
-I/usr/include/c++/13 \
-I/usr/include/x86_64-linux-gnu/c++/13 \
-o test \
src/main.cpp
# nm -C test | grep basic_string
0000000001001500 T foo(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
-isystemの代わりに-Iを使用することで、エラーが解消されただけでなく、C++ランタイムのABIもlibstdc++の__cxx11となっていた。
ところでこのビルドではC++ランタイムをリンクしていない。
なのになぜビルドが成功したのか?
それは、std::stringを引数に持つ関数を作成はしたが呼んでいないため、std::stringのテンプレートが実体化されず、結果リンク不要となっていたからであった。
ということで次はstd::stringを使用するようmain.cppを変更する。
ビルドするソースファイル(2)
#include <string>
#include <iostream>
auto foo(std::string const&) -> void {}
auto main() -> int {
std::cout << std::string("Hello world") << std::endl;
return 0;
}
std::stringをインスタンス化している。
さっきのコマンドを実行する
# zig c++ \
-nostdinc++ \
-I/usr/include/c++/13 \
-I/usr/include/x86_64-linux-gnu/c++/13 \
-o test \
src/main.cpp
ld.lld: error: undefined symbol: std::cout
>>> referenced by main.cpp:7 (src/main.cpp:7)
>>> .zig-cache/o/5481eefaf6956e048d9962685de7812c/main.o:(main)
....(大量のリンクエラー)
当然の如くリンクエラーとなる。
ということからここで満を持してlibstdc++をリンクする。
# zig c++ \
-nostdinc++ \
-I/usr/include/c++/13 \
-I/usr/include/x86_64-linux-gnu/c++/13 \
-lstdc++ \
-o test \
src/main.cpp
In file included from src/main.cpp:1:
In file included from /usr/include/c++/13/string:54:
In file included from /usr/include/c++/13/bits/basic_string.h:4109:
In file included from /usr/include/c++/13/ext/string_conversions.h:43:
In file included from /usr/include/c++/13/cstdlib:81:
/usr/include/c++/13/bits/std_abs.h:71:3: error: declaration conflicts with target of using declaration already in scope
71 | abs(double __x)
...(大量のコンパイルエラー)
不思議なことにlibstdc++のライタイムを指定しただけでヘッダ衝突を起こしてしまった。
zig c++の呼び出しの際に--verboseを指定してみたところ
#include "..." search starts here:
#include <...> search starts here:
/usr/include/c++/13
/usr/include/x86_64-linux-gnu/c++/13
/opt/zig/lib/libcxx/include
/opt/zig/lib/libcxxabi/include
/opt/zig/lib/include
/usr/include
/usr/include/x86_64-linux-gnu
/usr/local/include
/opt/zig/lib/libunwind/include
のようにlibstdc++とlibc++の両方のヘッダが取り込まれていた。
どうもこれがヘッダ衝突の原因のようである。
ということで-lstdc++のランタイムを指定することはできないようである。
ここで行き詰まる。
チャッピーと殴り合った結果、C++ランタイムをオブジェクトファイルとして指定すればいけるのではというところに行き着く。
# zig c++ \
-nostdinc++ \
-I/usr/include/c++/13 \
-I/usr/include/x86_64-linux-gnu/c++/13 \
-o test \
/usr/lib/gcc/x86_64-linux-gnu/13/libstdc++.so \
src/main.cpp
ld.lld: error: undefined symbol: _Unwind_Resume
>>> referenced by main.cpp:0 (src/main.cpp:0)
>>> .zig-cache/o/5481eefaf6956e048d9962685de7812c/main.o:(main)
>>> referenced by basic_string.h:650 (/usr/include/c++/13/bits/basic_string.h:650)
>>> .zig-cache/o/5481eefaf6956e048d9962685de7812c/main.o:(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>::basic_string<std::allocator<char>>(char const*, std::allocator<char> const&))
>>> referenced by basic_string.tcc:0 (/usr/include/c++/13/bits/basic_string.tcc:0)
>>> .zig-cache/o/5481eefaf6956e048d9962685de7812c/main.o:(void std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>::_M_construct<char const*>(char const*, char const*, std::forward_iterator_tag))
標準C++のリンクエラーが解消され、_Unwind_Resumeのみ未解決となった。
これはgccによって提供される組み込み関数であり/usr/lib/x86_64-linux-gnu/libgcc_s.so.1で提供されている。
ということでそれを加えて再度トライ。
# zig c++ \
-nostdinc++ \
-I/usr/include/c++/13 \
-I/usr/include/x86_64-linux-gnu/c++/13 \
-o test \
/usr/lib/gcc/x86_64-linux-gnu/13/libstdc++.so \
/usr/lib/x86_64-linux-gnu/libgcc_s.so.1 \
src/main.cpp
# ./test
Hello world
# nm -C test | grep basic_string
0000000001015a40 T foo(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
無事ビルドに成功して実行も確認でき、ランタイムとしてlibstdc++がリンクされていることが確認できた。
build.zigでの指定
以上の検証結果はそのままbuild.zigのビルド構成として展開できる。
const exe = b.addExecutable(.{
.name = "cpp_abi",
.root_module = b.createModule(.{
.target = target,
.optimize = optimize,
.link_libcpp = false,
.link_libc = true,
}),
});
exe.root_module.addCSourceFiles(.{
.root = b.path("src"),
.files = &.{
"main.cpp",
},
.flags = &.{
"-std=c++20",
},
});
exe.root_module.addIncludePath(.{.cwd_relative = "/usr/include/c++/13"});
exe.root_module.addIncludePath(.{.cwd_relative = "/usr/include/x86_64-linux-gnu/c++/13"});
exe.root_module.addIncludePath(.{.cwd_relative = "/usr/include"});
exe.root_module.addIncludePath(.{.cwd_relative = "/usr/include/x86_64-linux-gnu"});
exe.root_module.addObjectFile(.{.cwd_relative = "/usr/lib/gcc/x86_64-linux-gnu/13/libstdc++.so"});
exe.root_module.addObjectFile(.{.cwd_relative = "/usr/lib/x86_64-linux-gnu/libgcc_s.so.1"});
b.installArtifact(exe);
-
libc++を無効にするため、.link_libcpp = false- デフォルト構成だけど明示的に指定した
-
glibcをリンクさせるため.link_libc = true-
cabiにC++のようにランタイムごとにABIが異なるということがないため特別な小細工は不要
-
- 標準Cと標準
C++のインクルードパスを構成する-
zig c++では標準Cのインクルードパスの指定は不要だったが、build.zigだとコンパイルエラーになったため - なんか足したら通ったのでヨシ
-
-
C++ランタイムとgccランタイムをオブジェクトファイルとして構成する
この構成でzig buildを実行することで、zig c++同様期待通りlibstdc++がリンクされた成果物を生成することができた。
なぜlibstdc++を直接指定した場合にヘッダ衝突を起こしたのか
std.Build.Module.addSystemLibrary()の定義に秘密が隠されていた。
pub fn linkSystemLibrary(
m: *Module,
name: []const u8,
options: LinkSystemLibraryOptions,
) void {
const b = m.owner;
const target = m.requireKnownTarget();
if (std.zig.target.isLibCLibName(target, name)) {
m.link_libc = true;
return;
}
if (std.zig.target.isLibCxxLibName(target, name)) {
m.link_libcpp = true;
return;
}
m.link_objects.append(b.allocator, .{
.system_lib = .{
.name = b.dupe(name),
.needed = options.needed,
.weak = options.weak,
.use_pkg_config = options.use_pkg_config,
.preferred_link_mode = options.preferred_link_mode,
.search_strategy = options.search_strategy,
},
}) catch @panic("OOM");
}
pub fn isLibCLibName(target: *const std.Target, name: []const u8) bool {
const ignore_case = target.os.tag.isDarwin() or target.os.tag == .windows;
if (eqlIgnoreCase(ignore_case, name, "c"))
return true;
...
}
pub fn isLibCxxLibName(target: *const std.Target, name: []const u8) bool {
const ignore_case = target.os.tag.isDarwin() or target.os.tag == .windows;
return eqlIgnoreCase(ignore_case, name, "c++") or
eqlIgnoreCase(ignore_case, name, "stdc++") or
eqlIgnoreCase(ignore_case, name, "c++abi") or
eqlIgnoreCase(ignore_case, name, "supc++");
}
この関数ではcとc++のライタイムを指定する場合に特別処理が施されており、特にc++ではc++, stdc++, c++abi, supc++が指定された場合に、リンク構成に加えるのではなく、std.Build.Module.link_libcpp = trueとしていた。
このためにlibc++の構成が有効となってしまい、結果直接指定したlibstdc++の構成結果とバッティングしてヘッダが衝突したものと思われる。
zig c++のソースコードは追いかけていないが、おそらく同じような記述がされていると推測される。
おわりに
以上悪戦苦闘の末に、zigにstdlibc++を使わせるようわからせることに成功した。
これはLinux用に提供されるC++ABIなパッケージのAPIを使いそれを組み込むことができることを意味する(はず)。
おまけ
中の人曰く
C++ pretends to have an ABI, but it's a lie. That's the crucial problem here.
Zig provides libc++, however the libc++ that zig provides cannot be mixed with any C++ objects compiled from other compilers. If you do, you get undefined behavior. So you can't use zig c++ on libonnx2c_lib.a or /usr/local/lib/libprotobuf.so because these C++ objects were compiled with something other than zig c++.
I'm upset that C++ works this way but there is nothing we can do about it.
zig c++ is a drop-in C++ compiler if you use it for all your C++ objects; if not, it does not help you.
https://github.com/ziglang/zig/issues/9832#issuecomment-926832810
とのことのようなので用法・容量を守ってご利用は計画的に行う必要があるかも。
個人的にはCIでテスト回すくらいなら問題なくね?と楽観視してるけど。