2

I'm trying to debug the simple Hello World program that ships with Eclipse CDT. Running the program normally works fine, but when its run through debug mode, puts() doesn't print anything to the console.

I tried running the same program with gdb directly and it works fine, printing "!!!Hello World!!!" as expected.

Why doesn't puts() print anything when running in debug mode through Eclipse?

I'm on Windows with MinGW installed, running gcc 4.5.0, gdb 7.2, and CDT 7.0.1

3 Answers 3

4

Thanks to Swiss pointed out the right direction.
Adding fflush(stdout) after every printf,puts sentence is not suitable for a large project when debugging (When releasing, your'd better using fflush() at a appropriate time).
Then, we can use Preprocessor directives #ifdef && setbuf().
In Eclipse , your C project -> properties -> C/C++ Build -> Settings : Confgiguration = "Debug [ Active ]" -> Tool Settings -> GCC C Compiler -> Symbols -> Add "_DEBUG",

Then in your main(), using:

#ifdef _DEBUG
setbuf(stdout,NULL); // this disables buffering for stdout.
#endif
Sign up to request clarification or add additional context in comments.

Comments

1

Have you tried to append \n in the puts statement? I.e. puts("Hello World!\n"); Some times terminal needs \n to flush the stream.

1 Comment

This didn't work, but it made me realize that the buffer might not be flushing. Thanks for pointing me in the right direction!
1

I figured out why this happens. When running GDB through a terminal, STDOUT is line buffered, which means that it will be flushed every time a newline is read, resulting in the behavior I was expecting.

HOWEVER! Eclipse CDT runs GDB with STDOUT in block buffered mode, which means it will only flush STDOUT when it reaches a certain size, or if it is manually flushed. Since the string "!!!Hello World!!!" is so short, the buffer for STDOUT will never be flushed unless a call to fflush() is made.

I managed to fix this problem by adding fflush(stdout); after the call to puts().

Here's the resulting code:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    puts("Hello World!"); /* prints !!!Hello World!!! */
    fflush(stdout);
    return EXIT_SUCCESS;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.