In order to ensure that the asprintf
function is visible in the header file <stdio.h>
, I have followed the advice of the man page and put:
为了确保在头文件
#define _GNU_SOURCE
#include <stdio.h>
// ... uses of asprintf();
This works in normal C programs, although presumably only on GNU/Linux and not on the BSDs.
这适用于普通的C程序,虽然可能只在GNU / Linux上而不在BSD上。
I would like to be able to use the same trick in a flex lexer, e.g.:
我希望能够在flex lexer中使用相同的技巧,例如:
%{
#define _GNU_SOURCE
#include <stdio.h>
%}
%%
\"[^\"].+\" {
asprintf(&(yylval.string), "%s", yytext);
return STRING;
}
%%
// ...
but I get a compile warning (implicit-function-declaration
) for asprintf
.
但是我得到了asprintf的编译警告(implicit-function-declaration)。
Upon further investigation, this is because in the C file that flex generates it includes <stdio.h>
before my preamble code, without defining _GNU_SOURCE first.
经过进一步调查,这是因为在flex文件生成的C文件中,我在前导代码之前包含了
How can I write code which uses this function which
如何编写使用此功能的代码
- compiles correctly inside flex rules, and
- 在flex规则中正确编译,和
- (optionally) also works in non-GNU environments?
- (可选)也适用于非GNU环境?
1 个解决方案
#1
2
Having re-checked the book that got me into the habit of using asprintf
, I have discovered that it is indeed a GNU extension.
重新检查了让我习惯使用asprintf的书,我发现它确实是一个GNU扩展。
It is available in a GCC library called libiberty
, which you can use in place of the _GNU_SOURCE
macro.
它在名为libiberty的GCC库中可用,您可以使用它来代替_GNU_SOURCE宏。
I was able to install this on Ubuntu 15.10 and Debian 8.2 using:
我可以在Ubuntu 15.10和Debian 8.2上使用以下命令安装:
sudo apt-get install libiberty-dev
I then modified the preamble to include:
然后,我修改了序言,包括:
%{
#include <libiberty/libiberty.h>
%}
and everything worked without any warnings.
一切都没有任何警告。
Assuming that a libiberty package is available for non-Linux distributions (and given that it is part of GCC I would assume this would be the case) this solution should work cross platform (on POSIX-ish OS's.)
假设libiberty软件包可用于非Linux发行版(并且鉴于它是GCC的一部分,我认为会是这种情况),这个解决方案应该跨平台工作(在POSIX-ish操作系统上)。
#1
2
Having re-checked the book that got me into the habit of using asprintf
, I have discovered that it is indeed a GNU extension.
重新检查了让我习惯使用asprintf的书,我发现它确实是一个GNU扩展。
It is available in a GCC library called libiberty
, which you can use in place of the _GNU_SOURCE
macro.
它在名为libiberty的GCC库中可用,您可以使用它来代替_GNU_SOURCE宏。
I was able to install this on Ubuntu 15.10 and Debian 8.2 using:
我可以在Ubuntu 15.10和Debian 8.2上使用以下命令安装:
sudo apt-get install libiberty-dev
I then modified the preamble to include:
然后,我修改了序言,包括:
%{
#include <libiberty/libiberty.h>
%}
and everything worked without any warnings.
一切都没有任何警告。
Assuming that a libiberty package is available for non-Linux distributions (and given that it is part of GCC I would assume this would be the case) this solution should work cross platform (on POSIX-ish OS's.)
假设libiberty软件包可用于非Linux发行版(并且鉴于它是GCC的一部分,我认为会是这种情况),这个解决方案应该跨平台工作(在POSIX-ish操作系统上)。