Chris Allen
Chris Allen

Reputation: 713

popen implicitly declared even though #include <stdio.h> is added

This is tiny snippet of my code.

   #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

I'm really unsure. I looked up popen and all it requires is stdio.h which is provided. What is missing, or is the problem in the rest of my code (I don't really want to show more code because its an a assignment).

Upvotes: 23

Views: 12388

Answers (5)

creativeAxe
creativeAxe

Reputation: 119

As others like @Conrad Mayer has commented.

Succinty, just add

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

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

Explanation

The popen() function is part of the POSIX standard, and its declaration might depend on the feature test macros being properly defined.This should ensure that the necessary declarations for popen() are available.

If the issue persists, you can try defining _GNU_SOURCE before including headers, as popen() is also a GNU extension:

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

Upvotes: 0

Raptor007
Raptor007

Reputation: 398

I ran into this problem in MinGW; in its stdio.h I found:

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

And it turns out I had -DNO_OLDNAMES=1 on my gcc command line to fix some obscure problem in another source file that I can't even recall anymore. This was my easy fix:

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

Upvotes: 0

weakish
weakish

Reputation: 29952

Replace -std=c99 or -std=c11 etc with -std=gnu99 or -std=gnu11.

Upvotes: 17

Chris Allen
Chris Allen

Reputation: 713

I put the prototypes of popen and pclose at the top of my code. It seemed to have settled the problem.

Upvotes: -6

Conrad Meyer
Conrad Meyer

Reputation: 2897

As the man page says:

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

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

So you should #define _BSD_SOURCE or one of the others before #includeing stdio.h.

Upvotes: 15

Related Questions