Use GNU versions of basename() and dirname() in C source

Roman A. Taycher picture Roman A. Taycher · Apr 27, 2011 · Viewed 14.6k times · Source

How do I use the GNU C Library version of basename() and dirname()?.

If you

#include <libgen.h>

for dirname You're already getting the POSIX, not the GNU, version of basename(). (Even if you

#define _GNU_SOURCE

As far as I know there is no conditional importing in C. Is there a gcc specific trick?

Answer

R.. GitHub STOP HELPING ICE picture R.. GitHub STOP HELPING ICE · Apr 27, 2011

Just write it yourself and give it a different name than basename. This GNU insistence on creating alternate non-conforming versions of standard functions that can be written in 1-3 lines is completely batty.

char *gnu_basename(char *path)
{
    char *base = strrchr(path, '/');
    return base ? base+1 : path;
}

This way, your program will also be more portable.