strndup有什么问题?

时间:2011-05-19 17:55:50

标签: c macos flex-lexer

我正在使用flex编写解析器。我使用的是Mac OS X 10.6.7。 我已经包含了这样的头文件:

#include "string.h"
#include "stdlib.h"

但它说

Undefined symbols for architecture x86_64:
  "_strndup", referenced from:
      _yylex in ccl2332A.o
ld: symbol(s) not found for architecture x86_64

为什么?

3 个答案:

答案 0 :(得分:5)

AFAIK在string.h或stdlib.h中没有方法strndup,尝试使用strdup(),这可能是你想要的。如果你真的需要指定你想要分配的长度,你可以使用malloc和memcpy代替。

答案 1 :(得分:3)

strndup是一个GNU扩展,在Mac OS X上不存在。您必须不使用它或提供某些实现,例如this one

答案 2 :(得分:0)

如果您需要strndup实现,可以使用此实现。

char *strndup(char *str, int chars)
{
    char *buffer;
    int n;

    buffer = (char *) malloc(chars +1);
    if (buffer)
    {
        for (n = 0; ((n < chars) && (str[n] != 0)) ; n++) buffer[n] = str[n];
        buffer[n] = 0;
    }

    return buffer;
}