-2

I'm trying to write and run "Hello World" in C.

    int main(int argc, char *argv[])
{
    #include <stdio.h>
    puts("Hello world.");

    return 0;
}

However, I keep getting the following error in the Terminal:

In file included from ex.c:3:
/usr/include/stdio.h:353:54: error: function definition is not allowed here
__header_always_inline int __sputc(int _c, FILE *_p) {
                                                     ^
1 error generated.

It appears to me it's picking up a syntax error in the stdio header file? I don't understand what's happening.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

2 Answers2

1

You want to do something like this:

#include <stdio.h>

int main(void)
{
    puts("Hello world.");
    return 0;
}

Your #include directives should pretty much always come first in your file. When you write #include <some_file>, you're telling the preprocessor to basically copy all the text from some_file into your program. For example, <stdio.h> includes the puts function declaration. By including <stdio.h> as the first thing in the file, you're able to tell the compiler about puts so that it can use it later on.

Edit: thanks @Olaf for pointing out that #include is a directive and not a statement

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Zexus
  • 173
  • 6
0

Section 7.1.2 Standard headers of the C standard says, in part:

If used, a header shall be included outside of any external declaration or definition, and it shall first be included before the first reference to any of the functions or objects it declares, or to any of the types or macros it defines.

That means you are not allowed to include any of the standard headers inside the body of a function.

Your code is violating that rule — it isn't required to work. Don't do it!

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278