Dramal
Dramal

Reputation: 177

What could be delaying the printf output of my C program?

A simplified version of my code is:

#include "externalstuff.h"
void main(){
    printf("Hello?");
    /* make calls to externalstuff
    ....
    */
}

I did not write externalstuff.h, so I'm not sure what is going on there exactly.

The calls to externalstuff take some time to execute. I would expect that "Hello?" would get printed, then I would have to wait for those external calls to finish, then my program would end. But what seems to be happening is that "Hello?" only gets printed right before my program ends, after a long wait for the externalstuff.

Is it possible that something in externalstuff.h is delaying this output? If so, how?

I'm using gcc in cygwin on Widnows 7.

Upvotes: 5

Views: 1957

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Buffering delays the output of your program. When you call printf, the output is stored in a buffer until one of three things happen:

  • The length of internal buffer becomes insufficient for holding the output, or
  • You call fflush(stdout) to initiate sending the buffer to console explicitly, or
  • You print '\n' character, and the output is sent to console (as opposed to sending the output to a file).

If you don't like this behavior, and do not mind somewhat slower performance, you can call

setbuf(stdout, NULL);

to disable buffering.

Upvotes: 11

Related Questions