4

I have a c file that I can compile with no problem using GCC like below:

gcc foo.c

however using the same file I am receiving error of having defined functions inside main using clang:

clang foo.c

foo:230:1: error: function definition is not allowed here
{
^
foo.c:241:1: error: function definition is not allowed here
{
^
foo.c:253:1: error: function definition is not allowed here

these instances of errors are the definitions of a new function inside the main section of the code. I want to know why GCC doesn't get bothered with this yet clang does?

Amir
  • 1,348
  • 3
  • 21
  • 44

1 Answers1

5

Functions defined within functions are an extension to the C language, implemented by gcc. This is enabled by default. If you make gcc a Standard C compiler, as with -ansi -pedantic or -std=C99 or similar, it will also complain about nested function definitions:

x.c: In function ‘main’:
x.c:8:5: warning: ISO C forbids nested functions [-Wpedantic]
     int nested(void)
     ^
Jens
  • 69,818
  • 15
  • 125
  • 179
  • 2
    thanks @Jens. Do you know whether or not this had been implemented in clang as well? – Amir May 08 '17 at 16:07
  • 2
    @Amir As of clang 4.0.0, clang doesn't support nested functions. Why would you want them? If you are in control of the source code, you can rewrite the source and move the nested functions to file scope. – Jens May 08 '17 at 16:53
  • 9
    @Jens Nested functions are sometimes useful. For instance, we use them in GNU MPFR for (optional) logging support: such functions are defined via a macro expansion used inside a function. Getting rid of nested functions would mean splitting macros and making sure that there are no conflicts between identifiers, and this would make the code less readable and less maintainable. – vinc17 Jun 21 '19 at 17:22
  • 5
    @Jens: nested functions are akin to C++ lambdas -- they can access the enclosing function variables. Unlike C++ lambdas, though, they are convertible to a simple function pointer even when they do access the enclosing scope. The former can be done by relocating the function to the global scope and passing an extra context argument down the call chain (though it is verbose), the later cannot be done without compiler support for nested function. – Yakov Galka Dec 13 '19 at 22:16
  • 2
    @Jens, "why would you want functions in file scope? If you are in control of the source code, you can rewrite the entire program in `main` and use `goto`s to jump around as necessary. Or you can just rewrite the source in assembly." Yeesh... Are we _seriously_ on a programming site asking "why would you do X in language Y when I can think of method Z to achieve a similar result in a more verbose fashion?" – SO_fix_the_vote_sorting_bug Dec 28 '22 at 04:45