如何在不收到以下警告的情况下使用gcc编译lex文件?
lex.yy.c: In function `yy_init_buffer':
lex.yy.c:1688: warning: implicit declaration of function `fileno'
lex.l: In function `storeLexeme':
lex.l:134: warning: implicit declaration of function `strdup'
这些是我包含的库。
%{
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
%}
函数yy_init_buffer不在文件中。以下是函数storeLexeme。
int storeLexeme() {
for (int i = 0; i < count; i++) {
char *curr = *(symbolTable + i);
if (strcmp(curr, yytext) == 0) {
return i;
}
}
char *lexeme = (char *)malloc(sizeof(char *));
lexeme = (char *)strdup(yytext);
symbolTable[count] = lexeme;
count++;
return (count - 1);
}
如何删除警告?
答案 0 :(得分:11)
strdup
和fileno
都不是ISO C函数,它们是POSIX的一部分。
现在,您的平台上是否可以使用它们取决于您的平台。
如果您使用的是Microsoft工具,则可能需要查看_fileno
后者(VC2005中为fileno
was deprecated)。可以找到strdup
的相当出色的版本here。
虽然使用该代码吹响了自己的号角,但您也可以使用_strdup
,因为它取代了also-deprecated strdup
: - )
这些应该可以正常工作,因为它们位于您已使用的两个包含文件的stdio.h
和string.h
中。
如果您使用的是UNIX衍生产品,则stdio.h
(适用于fileno
)和string.h
(适用于strdup
)应提供这些功能。鉴于您看起来已经包含了这些文件,问题可能出在其他地方。
一种可能性是,如果您正在使用gcc中的__STRICT_ANSI__
之类的严格模式进行编译,那么两者都不会被定义。
您应该查看生成的lex.yy.c
和lex.l
文件的顶部以确认包含的头文件 ,并检查命令行参数'传递给编译器。
答案 1 :(得分:9)
我建议这个选项(告诉编译器你正在使用POSIX):
#define _POSIX_C_SOURCE 1
近年来,人们似乎已经收紧了功能控制,希望当一致性良好且普遍存在时,我们可以抛弃自动化垃圾。
答案 2 :(得分:5)
考虑添加以下行:
extern char *strdup(const char *s);
我用-std=c99 -pedantic -pedantic-errors
编译时遇到了问题。添加上述代码就解决了我的问题。
答案 3 :(得分:4)
使用flex时我也遇到了这个问题。
我使用-std=gnu99
而不是-std=c99
来解决问题。
flex lang.l && gcc -o lexer -std=gnu99 lex.yy.c -lfl
答案 4 :(得分:0)
在使用之前声明该函数:
//declare the function
int storeLexeme();
//use the function here
或包含声明函数的标题。
C隐式假设未声明的函数具有返回类型int
,并从您调用函数的方式中推导出参数。这在C ++中已弃用。