basename()
およびの GNU C ライブラリ バージョンを使用するにはどうすればよいdirname()
ですか?.
もし、あんたが
#include <libgen.h>
for dirname の GNU バージョンではなく、POSIX バージョンを既に取得していますbasename()
。(たとえあなたが
#define _GNU_SOURCE
私の知る限り、C には条件付きインポートはありません。gcc 固有のトリックはありますか?
自分で書いて、とは別の名前を付けてくださいbasename
。1〜3行で記述できる標準関数の代替の非準拠バージョンを作成するというこのGNUの主張は、完全にばかげています。
char *gnu_basename(char *path)
{
char *base = strrchr(path, '/');
return base ? base+1 : path;
}
このようにして、プログラムの移植性も向上します。
マニュアルページによると、あなたがすべきこと
#define _GNU_SOURCE
#include <string.h>
#include <libgen.h>
POSIX バージョンを取得した場合、libgen.h はおそらくその時点より前に既に含まれています。-D_GNU_SOURCE
コンパイルのために CPPFLAGSに含めることができます。
gcc -D_GNU_SOURCE ....
を調べた後libgen.h
、警告とエラーのない解決策があると確信しています。
/* my C program */
#define _GNU_SOURCE /* for GNU version of basename(3) */
#include <libgen.h> /* for dirname(3) */
#undef basename /* (snide comment about libgen.h removed) */
#include <string.h> /* for basename(3) (GNU version) and strcmp(3) */
/* rest of C program... */
この#undef
行により、私のプログラムにはdirname(3)
fromとfromlibgen.h
の GNU バージョンが含まれるようになりました。basename(3)
string.h
gcc
(バージョン 4.5.2) またはclang
(バージョン 3.3)からのコンパイラ警告/エラーはありません。
システムの (推定される) POSIX 互換のデフォルトではなく、GNU C ライブラリを使用してビルドしていることを確認してください。
多くの場合、これは GCC 仕様ファイルで設定されます。-vオプションを使用して、現在の設定を表示します。
$ gcc -v
Using built-in specs.
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.4.4-14ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.4 --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.4.5 (Ubuntu/Linaro 4.4.4-14ubuntu5)