Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

posix

gnu

dirname

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?

like image 868
Roman A. Taycher Avatar asked Apr 27 '11 09:04

Roman A. Taycher


2 Answers

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.

like image 105
R.. GitHub STOP HELPING ICE Avatar answered Oct 05 '22 02:10

R.. GitHub STOP HELPING ICE


According to the man page you should do

      #define _GNU_SOURCE
       #include <string.h>
       #include <libgen.h>

If you get the POSIX version, libgen.h is probably already included before that point. You may want to include -D_GNU_SOURCE in the CPPFLAGS for compilation:

gcc -D_GNU_SOURCE ....
like image 30
sehe Avatar answered Oct 05 '22 01:10

sehe