LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Error for a very simple C program (https://www.linuxquestions.org/questions/linux-newbie-8/error-for-a-very-simple-c-program-156280/)

pkashyap 03-11-2004 08:54 AM

Error for a very simple C program
 
Hi there,

I am a newbie to Linux. The objective of mine is to learn programming on Linux and get rid of Windows. I hate Windows.

In LINUX Answers section of this forum, a simple program of C is published. The program does just a simple printf of some text and nothing else. I am getting an error in Linux.

I have Linux red hat 9. To cross check if C compiler is present, I did a
" which gcc " command in the terminal. I got a reply /usr/bin/gcc . I assume that this means that the compiler is present on the system.

On writing the simple following program:

# include<stdio.h>

main()
{
printf("Linuxquestions.org\n");
}

I get an error which says :

bash:syntax error near unexpected token '(printf '

I wonder what this means. Help on this regard would be appreciated.

Also, it would be great if people can suggest some good books to buy for programming C on Linux.

Thanks in advance for your help.

Cheers

PK

P.S : I have logged on as localhost : root. Could this be a reason for the error? Just thinking aloud ..................

skel 03-11-2004 09:08 AM

you have to compile the source code

gcc -o executable filename.c

replace executable with the name you want and filename with the name of the source file.

and then run ./executable

What you are trying to do is run the source code as an executable. C is a compiled language, so you have to run gcc on your source code to turn it into machine language

skel

Mega Man X 03-11-2004 10:24 AM

Code:

# include<stdio.h>

main()
{
    printf("Linuxquestions.org\n");
}

You do, realize that all functions in C or C++ has to return a value, unless it's declared as void. main() is not an exception.

Code:

# include<stdio.h>

main()
{
    printf("Linuxquestions.org\n");
    return 0;
}

By default, all functions without explicit declaration, will be understood for the compiler as integer. You could declare it as void:
Code:

# include<stdio.h>

void main()
{
    printf("Linuxquestions.org\n");
}

and then you don't need to return any value. It's a good programing style to always declare a function explicitly.

Code:

# include<stdio.h>

int main()
{
    printf("Linuxquestions.org\n");
    return 0;
}

Regards!


All times are GMT -5. The time now is 06:01 PM.