即使添加了#include,也会隐式声明popen< stdio.h>

ldfqzlk8  于 8个月前  发布在  其他
关注(0)|答案(5)|浏览(96)

这是我的一小段代码。

#include <stdio.h>
   #include <unistd.h>
   #include <stdlib.h>
   #include <time.h>
   #include <sys/stat.h>
   #include <sys/wait.h>
   #include <sys/types.h>
   #include <string.h>
   #include <sys/types.h>
   #include <sys/socket.h>
   #include <netinet/in.h>
   #include <arpa/inet.h>
    ...

   FILE * pipe;
    ...

   pipe = popen ("ls /tmp -1", "r");
    ...
   pclose(pipe);
blarg.c:106: warning: implicit declaration of function ‘popen’

blarg.c:106: warning: assignment makes pointer from integer without a cast

blarg.c:112: warning: implicit declaration of function ‘pclose’

blarg.c:118: warning: assignment makes pointer from integer without a cast

我真的不确定。我查了一下popen,它所需要的只是提供的stdio. h。缺少了什么,或者说是我代码其余部分的问题(我真的不想显示更多的代码,因为这是一个赋值)。

vlurs2pr

vlurs2pr1#

-std=c99-std=c11等替换为-std=gnu99-std=gnu11

dm7nw8vv

dm7nw8vv2#

正如man page所说:

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

popen(), pclose(): _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE || _BSD_SOURCE
|| _SVID_SOURCE

所以你应该在#includestdio.h之前输入#define _BSD_SOURCE或其他值。

inkz8wg9

inkz8wg93#

我在MinGW遇到了这个问题;在它的stdio.h中,我发现:

#ifndef NO_OLDNAMES
_CRTIMP __cdecl __MINGW_NOTHROW  FILE *  popen (const char *, const char *);
_CRTIMP __cdecl __MINGW_NOTHROW  int     pclose (FILE *);
#endif

结果我在gcc命令行上使用了-DNO_OLDNAMES=1来修复另一个源文件中的一些模糊问题,我甚至记不起来了。这是我的简单解决方案:

#ifdef NO_OLDNAMES
  #undef NO_OLDNAMES
#endif
#include <stdio.h>
cwtwac6a

cwtwac6a4#

正如@Conrad Mayer等其他人评论的那样。
Succinty,只需添加

#define _POSIX_C_SOURCE 200809L  // Define this before any includes

#include <stdlib.h>
... rest of code ...

说明

popen()函数是POSIX标准的一部分,它的声明可能依赖于正确定义的功能测试宏。这应该确保popen()的必要声明可用。
如果问题仍然存在,您可以尝试在包含头文件之前定义_GNU_SOURCE,因为popen()也是一个GNU扩展:

#define _GNU_SOURCE
#include <stdlib.h> 
...
h7appiyu

h7appiyu5#

我把popen和pclose的原型放在代码的顶部。看来问题解决了。

相关问题