Search code examples
cexternstrtok

C define a macro function in header file pointing to an extern function


I have a question about function macro definition in C (I'm a beginner): I have a COTS library lib.a which uses strtok() function, but my CERT application only supports strtok_r, so I get an error at compile time.

How could I define in header file such that strtok function should be overridden with strtok_r?

I tried with something like this, but I get errors:

extern char *strtok_r(char *s1, const char *s2, char **saveptr);
#define strtok(s1,s2) strtok_r(s1,s2,saveptr)

Which is the best and clean way to achieve the result?

Thanks a lot for your inputs.


Solution

  • Assuming I understand you correctly:

    1. You do not have the strtok function available.
    2. You use a library libother.a (just to give it a name) that internally uses the strtok - function.
    3. You don't have the source code of this library.

    Rob is on the right track, but got it the wrong way round I think...

    You could build your own strtok function by wrapping the strtok_r function like this:

    Insert this function in one of your source files:

    char *strtok(char *s1, const char *delim) {
        static char* saveptr = 0;
        return strtok_r(s1, delim, &saveptr);
    }
    

    Then compiling and linking your code the usual way like

    gcc your_code_file.c -lother -o your_binary
    

    should do. However: There is a reasong why you should prefer to use strtok_r over strtok: strtok can only parse one string at a time, strtok_r allows to parse an arbitrary amount of different strings concurrently.

    With the 'hack' above you loose this advantage of strtok_r.