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.
Assuming I understand you correctly:
strtok
function available.libother.a
(just to give it a name) that internally uses the strtok
- function.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
.