[NTLUG:Discuss] Extremely simple C program...

Steve Baker sjbaker1 at airmail.net
Sat Aug 10 23:56:00 CDT 2002


Wayne Dahl wrote:

> Ok...I'm attempting to learn C for the very first time (I'm no
> programmer and I can hear the laughter now) from a book.

My 11 year old son is also learning C...you probably don't want
to know how easy he's finding it!

> #include <stdio.h>
> 
> void main()
> {
> 	printf("Hello world!");
> }
> 
> So far, so good.  After writing that in gedit and saving it as hello.c,
> I issue gcc -c hello.c and get these messages...

The '-c' argument to gcc says that you want it to compile this program
as far as the '.o' stage - but not link it to make a complete executable.

If your program is entirely contained in a single file, then you probably
want to leave off the '-c'.

     gcc hello.c

...generates an 'a.out' file that you can run.

However, that's kinda inconvenient - and you may actually prefer:

     gcc -o hello hello.c

The '-o hello' part tells it to write the resulting executable to a
file called 'hello' instead of 'a.out' (which is the default).

> hello.c: In function `main'
> hello.c:6: warning: return type of `main' is not `int'

This is only a warning.

Under UNIX/Linux, the 'main' function should return a result which
is zero for a program that worked OK - or some non-zero value if your
program thinks it failed to do it's job correctly.

So, the *correct* version of 'hello' is:

#include <stdio.h>

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

Notice I added a '\n' to the Hello World part - that's to put out
a newline at the end of the line - otherwise you'll get:

% hello
Hello World%

...with the cursor left hanging just after the '%' prompt.  That's
not exactly *wrong* but it's inconvenient.

> Then, when I attempt to link the two by using gcc hello.c hello.o, I get
> these messages...

Yes - that didn't work because gcc will attempt to compile 'hello.c' (again)
and then link it to 'hello.o' - which (of course) is the exact same program!
That triggered an error because there were then two functions - both called 'main'
and it didn't know which one was the 'real' one!

Just stick to:

    gcc -o hello hello.c                      -- This compiles the program
    ./hello                                   -- This runs the program

...until your programs get so huge that they need to be split into multiple
files.

Right now, you have enough other things to worry about - so just keep the
compiling simple and concentrate on learning the language.

----------------------------- Steve Baker -------------------------------
Mail : <sjbaker1 at airmail.net>   WorkMail: <sjbaker at link.com>
URLs : http://www.sjbaker.org
        http://plib.sf.net http://tuxaqfh.sf.net http://tuxkart.sf.net
        http://prettypoly.sf.net http://freeglut.sf.net
        http://toobular.sf.net   http://lodestone.sf.net






More information about the Discuss mailing list