user1451632 user1451632 - 1 month ago 4
C Question

Why do I get no output for very simple Hello World program?

I am wondering why my C program does not print any information. I am 100% new to programming, and have been able to learn a few things in Ruby and Python these past few weeks, but I am getting nowhere with the C stuff. Here is the total baseline, simple program that everyone learns first:

#include <stdio.h>

int main()

{
printf("Hello World\n");
return 0;
}


So I've got that written, and I save as hello.c. Now I cd to the directory where it is, and then I try

gcc hello.c


and nothing happens - no errors, just nothing. If I write instead

gcc hello.c -o hello


a new executable file is written to my directory, and when I open it, it looks like the normal command line, and has "Hello World" written there, as I expected in my terminal the first time.

I also tried make hello.c an executable itself, but when I do that I get

syntax error near unexpected token `('
`int main()'

Answer

When you type

gcc hello.c

and nothing happens, that is to be expected. Or more precisely, GCC will compile an executable with the default name, which for me is a.out. If I were then to type ./a.out on the command line, I see the output.

I think there may be a slightly bigger conceptual issue here though from your Ruby/Python background. Ruby and Python are (usually) interpreted languages, which means that when you create a script file, you can mark it as executable and through some magic the OS will start up a program that reads the files and executes them for you. C, however, is compiled. So when you run GCC, that takes your source file and turns it into an executable, with either the default or specified name. At this point, one would not expect to see any output unless there is a problem with the compilation process. Then you can run ./hello, which is an executable, and see your output.

That also explains why you can't mark hello.c as executable and run it. It needs to be compiled into an executable first. It looks like the system is pretending it's a shell script, which is isn't, and giving you a syntax error.

Comments