Loose-Info.com
Last Update 2021/12/28
TOP - 各種テスト - gcc - --sysroot=ディレクトリ

--sysroot=ディレクトリ
ヘッダやライブラリのルートディレクトリとしてディレクトリを使用

テスト概要

--sysroot=オプションを使用したコンパイル例

実行環境

GCC-8.2.0
GNU C Library 2.28
GNU Binutils 2.31.1


コード例・出力内容中の表記

・実行例中の太字表記部分は、コマンドなどの入力された文字列を示します。
・「」や「...」の着色省略表記は、 実際のソースコードや出力内容などを省略加工した部分を示します。

使用ファイル

使用ファイル一覧
. +-- func.c +-- sample.c +-- usr    +-- include    |   +-- stdio.h |    +-- lib    |   +-- libsamplefunc.so |    +-- local    +-- include    +-- func.h    +-- sample.h

usr/include/stdio.h
/usr/include/stdio.hを上記ディレクトリにコピー
インクルードガードを一部変更
#ifndef _STDIO_H #define _STDIO_H 2 <--- 変更(元ファイルは1)

usr/local/include/sample.h
#ifndef SAMPLE_H #define SAMPLE_H #include <func.h> #define SAMPLE 1 #endif /* SAMPLE_H */

usr/local/include/func.h
#ifndef FUNC_H #define FUNC_H #include <stdio.h> void sampFunc(void); #endif /* FUNC_H */

func.c
#include "func.h" void sampFunc(void) { printf("func\n"); }

sample.c
#include <sample.h> int main(void) { printf("SAMPLE = %d\n", SAMPLE); printf("_STDIO_H = %d\n", _STDIO_H); sampFunc(); return 0; }

動作テスト

func.cを共有ライブラリとしてコンパイル
--sysroot=オプションでルートディレクトリをカレントディレクトリ「.」に指定
エラー回避のため、-idirafterにより最終段階での/usr/include内の検索を指定
$ gcc -shared --sysroot=. -idirafter /usr/include -o libsamplefunc.so -fPIC func.c 共有ライブラリを「libsamplefunc.so」として生成 $ mv -v libsamplefunc.so usr/lib/ renamed 'libsamplefunc.so' -> 'usr/lib/libsamplefunc.so' $ コンパイル後、usr/lib/へ移動

sample.cをコンパイルして実行ファイルを生成
--sysroot=オプションでルートディレクトリをカレントディレクトリ「.」に指定
エラー回避のため、-idirafterにより最終段階での/usr/include内の検索を指定
実行時のライブラリへのパスを、リンカを対象とする-rpathオプションを利用してカレントディレクトリ内のusr/libに指定
$ gcc -v --sysroot=. -idirafter /usr/include sample.c -Wl,-rpath,usr/lib -lsamplefunc Using built-in specs. /usr/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/cc1 ... #include "..." search starts here: #include <...> search starts here: /usr/lib/gcc/x86_64-pc-linux-gnu/8.2.0/include ./usr/local/include /usr/lib/gcc/x86_64-pc-linux-gnu/8.2.0/include-fixed ./usr/include /usr/include End of search list. as -v --64 -o /tmp/ccz5nW12.o /tmp/ccnCkP6z.s /usr/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/collect2 ... $ ./a.out SAMPLE = 1 _STDIO_H = 2 func $ 青色部は--sysroot=により検索対象となったカレントディレクトリ内のディレクトリ