0

I want to use popen. It is in stdio.h. I include that, but the compiler doesn't see it with -std=c11. It does compile without -std=c11.

#include <stdio.h>

int main(void)
{
   popen("ls *","r");
}

gcc -std=c11 popen_test.c

popen_test.c: In function ‘main’:
popen_test.c:5:4: warning: implicit declaration of function ‘popen’ [-Wimplicit-function-declaration]

popen("ls *","r");
^~~~~

It is hidden in stdio.h with

#ifdef __USE_POSIX2

The man page says it is available if:

_POSIX_C_SOURCE >= 2 || /* Glibc versions <= 2.19: */ _BSD_SOURCE || _SVID_SOURCE

Scooter
  • 6,802
  • 8
  • 41
  • 64

1 Answers1

1

popen is not part of C. To get it, you need to enable it with a feature test macro before including anything.

The simplest way to do it is with a #define _GNU_SOURCE at the top (or with -D_GNU_SOURCE in your compiler invocation).

compiles with -std=c11:

#define _GNU_SOURCE
#include <stdio.h>

int main(void)
{
   popen("ls *","r");
}
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • Does -std=c11 mean "don't allow anything that isn't part of C11"? I was hoping for "allow anything that is part of C11". – Scooter Nov 10 '18 at 20:20
  • 1
    @Scooter I'd say it's more like that calling `gcc` without a specific standards gives you some extra gnu stuff (`-std=gnu11` or whatever your compiler defaults to). `-std=c11` disables it so that the identifiers that the C standard says should belong to you aren't taken. – Petr Skocik Nov 10 '18 at 20:23
  • 2
    @Scooter `int popen; int main(void) { return popen; }` is a valid C11 program, but it would conflict with the `popen` function. – melpomene Nov 10 '18 at 20:24